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.
11 //! Utilities for slice manipulation
13 //! The `slice` module contains useful code to help work with slice values.
14 //! Slices are a view into a block of memory represented as a pointer and a length.
18 //! let vec = vec!(1i, 2, 3);
19 //! let int_slice = vec.as_slice();
20 //! // coercing an array to a slice
21 //! let str_slice: &[&str] = ["one", "two", "three"];
24 //! Slices are either mutable or shared. The shared slice type is `&[T]`,
25 //! while the mutable slice type is `&mut[T]`. For example, you can mutate the
26 //! block of memory that a mutable slice points to:
29 //! let x: &mut[int] = [1i, 2, 3];
31 //! assert_eq!(x[0], 1);
32 //! assert_eq!(x[1], 7);
33 //! assert_eq!(x[2], 3);
36 //! Here are some of the things this module contains:
40 //! There are several structs that are useful for slices, such as `Items`, which
41 //! represents iteration over a slice.
45 //! A number of traits add methods that allow you to accomplish tasks with slices.
46 //! These traits include `ImmutableSlice`, which is defined for `&[T]` types,
47 //! and `MutableSlice`, defined for `&mut [T]` types.
49 //! An example is the method `.slice(a, b)` that returns an immutable "view" into
50 //! a `Vec` or another slice from the index interval `[a, b)`:
53 //! let numbers = [0i, 1i, 2i];
54 //! let last_numbers = numbers.slice(1, 3);
55 //! // last_numbers is now &[1i, 2i]
58 //! ## Implementations of other traits
60 //! There are several implementations of common traits for slices. Some examples
64 //! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
65 //! * `Hash` - for slices whose element type is `Hash`
69 //! The method `iter()` returns an iteration value for a slice. The iterator
70 //! yields references to the slice's elements, so if the element
71 //! type of the slice is `int`, the element type of the iterator is `&int`.
74 //! let numbers = [0i, 1i, 2i];
75 //! for &x in numbers.iter() {
76 //! println!("{} is a number!", x);
80 //! * `.mut_iter()` returns an iterator that allows modifying each value.
81 //! * Further iterators exist that split, chunk or permute the slice.
83 #![doc(primitive = "slice")]
86 use core::mem::size_of;
88 use core::prelude::{Clone, Collection, Greater, Iterator, Less, None, Option};
89 use core::prelude::{Ord, Ordering, RawPtr, Some, range};
91 use core::iter::{range_step, MultiplicativeIterator};
96 pub use core::slice::{Chunks, Slice, ImmutableSlice, ImmutablePartialEqSlice};
97 pub use core::slice::{ImmutableOrdSlice, MutableSlice, Items, MutItems};
98 pub use core::slice::{MutSplits, MutChunks, Splits};
99 pub use core::slice::{bytes, ref_slice, MutableCloneableSlice};
100 pub use core::slice::{Found, NotFound};
102 // Functional utilities
104 #[allow(missing_doc)]
105 pub trait VectorVector<T> {
106 // FIXME #5898: calling these .concat and .connect conflicts with
107 // StrVector::con{cat,nect}, since they have generic contents.
108 /// Flattens a vector of vectors of `T` into a single `Vec<T>`.
109 fn concat_vec(&self) -> Vec<T>;
111 /// Concatenate a vector of vectors, placing a given separator between each.
112 fn connect_vec(&self, sep: &T) -> Vec<T>;
115 impl<'a, T: Clone, V: Slice<T>> VectorVector<T> for &'a [V] {
116 fn concat_vec(&self) -> Vec<T> {
117 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
118 let mut result = Vec::with_capacity(size);
119 for v in self.iter() {
120 result.push_all(v.as_slice())
125 fn connect_vec(&self, sep: &T) -> Vec<T> {
126 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
127 let mut result = Vec::with_capacity(size + self.len());
128 let mut first = true;
129 for v in self.iter() {
130 if first { first = false } else { result.push(sep.clone()) }
131 result.push_all(v.as_slice())
137 /// An iterator that yields the element swaps needed to produce
138 /// a sequence of all possible permutations for an indexed sequence of
139 /// elements. Each permutation is only a single swap apart.
141 /// The Steinhaus-Johnson-Trotter algorithm is used.
143 /// Generates even and odd permutations alternately.
145 /// The last generated swap is always (0, 1), and it returns the
146 /// sequence to its initial order.
147 pub struct ElementSwaps {
148 sdir: Vec<SizeDirection>,
149 /// If `true`, emit the last swap that returns the sequence to initial
156 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
157 pub fn new(length: uint) -> ElementSwaps {
158 // Initialize `sdir` with a direction that position should move in
159 // (all negative at the beginning) and the `size` of the
160 // element (equal to the original index).
163 sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
169 enum Direction { Pos, Neg }
171 /// An `Index` and `Direction` together.
172 struct SizeDirection {
177 impl Iterator<(uint, uint)> for ElementSwaps {
179 fn next(&mut self) -> Option<(uint, uint)> {
180 fn new_pos(i: uint, s: Direction) -> uint {
181 i + match s { Pos => 1, Neg => -1 }
184 // Find the index of the largest mobile element:
185 // The direction should point into the vector, and the
186 // swap should be with a smaller `size` element.
187 let max = self.sdir.iter().map(|&x| x).enumerate()
189 new_pos(i, sd.dir) < self.sdir.len() &&
190 self.sdir[new_pos(i, sd.dir)].size < sd.size)
191 .max_by(|&(_, sd)| sd.size);
194 let j = new_pos(i, sd.dir);
195 self.sdir.as_mut_slice().swap(i, j);
197 // Swap the direction of each larger SizeDirection
198 for x in self.sdir.mut_iter() {
199 if x.size > sd.size {
200 x.dir = match x.dir { Pos => Neg, Neg => Pos };
203 self.swaps_made += 1;
206 None => if self.emit_reset {
207 self.emit_reset = false;
208 if self.sdir.len() > 1 {
210 self.swaps_made += 1;
213 // Vector is of the form [] or [x], and the only permutation is itself
214 self.swaps_made += 1;
222 fn size_hint(&self) -> (uint, Option<uint>) {
223 // For a vector of size n, there are exactly n! permutations.
224 let n = range(2, self.sdir.len() + 1).product();
225 (n - self.swaps_made, Some(n - self.swaps_made))
229 /// An iterator that uses `ElementSwaps` to iterate through
230 /// all possible permutations of a vector.
232 /// The first iteration yields a clone of the vector as it is,
233 /// then each successive element is the vector with one
236 /// Generates even and odd permutations alternately.
237 pub struct Permutations<T> {
242 impl<T: Clone> Iterator<Vec<T>> for Permutations<T> {
244 fn next(&mut self) -> Option<Vec<T>> {
245 match self.swaps.next() {
247 Some((0,0)) => Some(self.v.clone()),
249 let elt = self.v.clone();
250 self.v.as_mut_slice().swap(a, b);
257 fn size_hint(&self) -> (uint, Option<uint>) {
258 self.swaps.size_hint()
262 /// Extension methods for vector slices with cloneable elements
263 pub trait CloneableVector<T> {
264 /// Copies `self` into a new `Vec`.
265 fn to_vec(&self) -> Vec<T>;
267 /// Deprecated. Use `to_vec`.
268 #[deprecated = "Replaced by `to_vec`"]
269 fn to_owned(&self) -> Vec<T> {
273 /// Converts `self` into an owned vector, not making a copy if possible.
274 fn into_vec(self) -> Vec<T>;
276 /// Deprecated. Use `into_vec`
277 #[deprecated = "Replaced by `into_vec`"]
278 fn into_owned(self) -> Vec<T> {
283 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
284 /// Returns a copy of `v`.
286 fn to_vec(&self) -> Vec<T> { Vec::from_slice(*self) }
289 fn into_vec(self) -> Vec<T> { self.to_vec() }
292 /// Extension methods for vectors containing `Clone` elements.
293 pub trait ImmutableCloneableVector<T> {
294 /// Partitions the vector into two vectors `(a, b)`, where all
295 /// elements of `a` satisfy `f` and all elements of `b` do not.
296 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
298 /// Creates an iterator that yields every possible permutation of the
299 /// vector in succession.
304 /// let v = [1i, 2, 3];
305 /// let mut perms = v.permutations();
308 /// println!("{}", p);
312 /// # Example 2: iterating through permutations one by one.
315 /// let v = [1i, 2, 3];
316 /// let mut perms = v.permutations();
318 /// assert_eq!(Some(vec![1i, 2, 3]), perms.next());
319 /// assert_eq!(Some(vec![1i, 3, 2]), perms.next());
320 /// assert_eq!(Some(vec![3i, 1, 2]), perms.next());
322 fn permutations(self) -> Permutations<T>;
325 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
327 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
328 let mut lefts = Vec::new();
329 let mut rights = Vec::new();
331 for elt in self.iter() {
333 lefts.push((*elt).clone());
335 rights.push((*elt).clone());
342 /// Returns an iterator over all permutations of a vector.
343 fn permutations(self) -> Permutations<T> {
345 swaps: ElementSwaps::new(self.len()),
352 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
353 let len = v.len() as int;
354 let buf_v = v.as_mut_ptr();
357 for i in range(1, len) {
358 // j satisfies: 0 <= j <= i;
362 let read_ptr = buf_v.offset(i) as *const T;
364 // find where to insert, we need to do strict <,
365 // rather than <=, to maintain stability.
367 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
369 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
373 // shift everything to the right, to make space to
374 // insert this value.
376 // j + 1 could be `len` (for the last `i`), but in
377 // that case, `i == j` so we don't copy. The
378 // `.offset(j)` is always in bounds.
381 let tmp = ptr::read(read_ptr);
382 ptr::copy_memory(buf_v.offset(j + 1),
385 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
394 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
395 // warning: this wildly uses unsafe.
396 static BASE_INSERTION: uint = 32;
397 static LARGE_INSERTION: uint = 16;
399 // FIXME #12092: smaller insertion runs seems to make sorting
400 // vectors of large elements a little faster on some platforms,
401 // but hasn't been tested/tuned extensively
402 let insertion = if size_of::<T>() <= 16 {
410 // short vectors get sorted in-place via insertion sort to avoid allocations
411 if len <= insertion {
412 insertion_sort(v, compare);
416 // allocate some memory to use as scratch memory, we keep the
417 // length 0 so we can keep shallow copies of the contents of `v`
418 // without risking the dtors running on an object twice if
420 let mut working_space = Vec::with_capacity(2 * len);
421 // these both are buffers of length `len`.
422 let mut buf_dat = working_space.as_mut_ptr();
423 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
426 let buf_v = v.as_ptr();
428 // step 1. sort short runs with insertion sort. This takes the
429 // values from `v` and sorts them into `buf_dat`, leaving that
430 // with sorted runs of length INSERTION.
432 // We could hardcode the sorting comparisons here, and we could
433 // manipulate/step the pointers themselves, rather than repeatedly
435 for start in range_step(0, len, insertion) {
437 for i in range(start, cmp::min(start + insertion, len)) {
438 // j satisfies: start <= j <= i;
439 let mut j = i as int;
442 let read_ptr = buf_v.offset(i as int);
444 // find where to insert, we need to do strict <,
445 // rather than <=, to maintain stability.
447 // start <= j - 1 < len, so .offset(j - 1) is in
449 while j > start as int &&
450 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
454 // shift everything to the right, to make space to
455 // insert this value.
457 // j + 1 could be `len` (for the last `i`), but in
458 // that case, `i == j` so we don't copy. The
459 // `.offset(j)` is always in bounds.
460 ptr::copy_memory(buf_dat.offset(j + 1),
463 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
468 // step 2. merge the sorted runs.
469 let mut width = insertion;
471 // merge the sorted runs of length `width` in `buf_dat` two at
472 // a time, placing the result in `buf_tmp`.
474 // 0 <= start <= len.
475 for start in range_step(0, len, 2 * width) {
476 // manipulate pointers directly for speed (rather than
477 // using a `for` loop with `range` and `.offset` inside
480 // the end of the first run & start of the
481 // second. Offset of `len` is defined, since this is
482 // precisely one byte past the end of the object.
483 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
484 // end of the second. Similar reasoning to the above re safety.
485 let right_end_idx = cmp::min(start + 2 * width, len);
486 let right_end = buf_dat.offset(right_end_idx as int);
488 // the pointers to the elements under consideration
489 // from the two runs.
491 // both of these are in bounds.
492 let mut left = buf_dat.offset(start as int);
493 let mut right = right_start;
495 // where we're putting the results, it is a run of
496 // length `2*width`, so we step it once for each step
497 // of either `left` or `right`. `buf_tmp` has length
498 // `len`, so these are in bounds.
499 let mut out = buf_tmp.offset(start as int);
500 let out_end = buf_tmp.offset(right_end_idx as int);
502 while out < out_end {
503 // Either the left or the right run are exhausted,
504 // so just copy the remainder from the other run
505 // and move on; this gives a huge speed-up (order
506 // of 25%) for mostly sorted vectors (the best
508 if left == right_start {
509 // the number remaining in this run.
510 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
511 ptr::copy_nonoverlapping_memory(out, &*right, elems);
513 } else if right == right_end {
514 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
515 ptr::copy_nonoverlapping_memory(out, &*left, elems);
519 // check which side is smaller, and that's the
520 // next element for the new run.
522 // `left < right_start` and `right < right_end`,
523 // so these are valid.
524 let to_copy = if compare(&*left, &*right) == Greater {
529 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
535 mem::swap(&mut buf_dat, &mut buf_tmp);
540 // write the result to `v` in one go, so that there are never two copies
541 // of the same object in `v`.
543 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
546 // increment the pointer, returning the old pointer.
548 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
550 *ptr = ptr.offset(1);
555 /// Extension methods for vectors such that their elements are
557 pub trait MutableSliceAllocating<'a, T> {
558 /// Sorts the slice, in place, using `compare` to compare
561 /// This sort is `O(n log n)` worst-case and stable, but allocates
562 /// approximately `2 * n`, where `n` is the length of `self`.
567 /// let mut v = [5i, 4, 1, 3, 2];
568 /// v.sort_by(|a, b| a.cmp(b));
569 /// assert!(v == [1, 2, 3, 4, 5]);
571 /// // reverse sorting
572 /// v.sort_by(|a, b| b.cmp(a));
573 /// assert!(v == [5, 4, 3, 2, 1]);
575 fn sort_by(self, compare: |&T, &T| -> Ordering);
577 /// Consumes `src` and moves as many elements as it can into `self`
578 /// from the range [start,end).
580 /// Returns the number of elements copied (the shorter of `self.len()`
581 /// and `end - start`).
585 /// * src - A mutable vector of `T`
586 /// * start - The index into `src` to start copying from
587 /// * end - The index into `src` to stop copying from
592 /// let mut a = [1i, 2, 3, 4, 5];
593 /// let b = vec![6i, 7, 8];
594 /// let num_moved = a.move_from(b, 0, 3);
595 /// assert_eq!(num_moved, 3);
596 /// assert!(a == [6i, 7, 8, 4, 5]);
598 fn move_from(self, src: Vec<T>, start: uint, end: uint) -> uint;
601 impl<'a,T> MutableSliceAllocating<'a, T> for &'a mut [T] {
603 fn sort_by(self, compare: |&T, &T| -> Ordering) {
604 merge_sort(self, compare)
608 fn move_from(self, mut src: Vec<T>, start: uint, end: uint) -> uint {
609 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
612 cmp::min(self.len(), end-start)
616 /// Methods for mutable vectors with orderable elements, such as
617 /// in-place sorting.
618 pub trait MutableOrdSlice<T> {
619 /// Sorts the slice, in place.
621 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
626 /// let mut v = [-5i, 4, 1, -3, 2];
629 /// assert!(v == [-5i, -3, 1, 2, 4]);
633 /// Mutates the slice to the next lexicographic permutation.
635 /// Returns `true` if successful and `false` if the slice is at the
636 /// last-ordered permutation.
641 /// let v = &mut [0i, 1, 2];
642 /// v.next_permutation();
643 /// assert_eq!(v, &mut [0i, 2, 1]);
644 /// v.next_permutation();
645 /// assert_eq!(v, &mut [1i, 0, 2]);
647 fn next_permutation(self) -> bool;
649 /// Mutates the slice to the previous lexicographic permutation.
651 /// Returns `true` if successful and `false` if the slice is at the
652 /// first-ordered permutation.
657 /// let v = &mut [1i, 0, 2];
658 /// v.prev_permutation();
659 /// assert_eq!(v, &mut [0i, 2, 1]);
660 /// v.prev_permutation();
661 /// assert_eq!(v, &mut [0i, 1, 2]);
663 fn prev_permutation(self) -> bool;
666 impl<'a, T: Ord> MutableOrdSlice<T> for &'a mut [T] {
669 self.sort_by(|a,b| a.cmp(b))
672 fn next_permutation(self) -> bool {
673 // These cases only have 1 permutation each, so we can't do anything.
674 if self.len() < 2 { return false; }
676 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
677 let mut i = self.len() - 1;
678 while i > 0 && self[i-1] >= self[i] {
682 // If that is the entire vector, this is the last-ordered permutation.
687 // Step 2: Find the rightmost element larger than the pivot (i-1)
688 let mut j = self.len() - 1;
689 while j >= i && self[j] <= self[i-1] {
693 // Step 3: Swap that element with the pivot
696 // Step 4: Reverse the (previously) weakly decreasing part
697 self.mut_slice_from(i).reverse();
702 fn prev_permutation(self) -> bool {
703 // These cases only have 1 permutation each, so we can't do anything.
704 if self.len() < 2 { return false; }
706 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
707 let mut i = self.len() - 1;
708 while i > 0 && self[i-1] <= self[i] {
712 // If that is the entire vector, this is the first-ordered permutation.
717 // Step 2: Reverse the weakly increasing part
718 self.mut_slice_from(i).reverse();
720 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
721 let mut j = self.len() - 1;
722 while j >= i && self[j-1] < self[i-1] {
726 // Step 4: Swap that element with the pivot
733 /// Unsafe operations
735 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
736 pub use core::slice::raw::{shift_ptr, pop_ptr};
742 use std::default::Default;
745 use std::rand::{Rng, task_rng};
750 use {Mutable, MutableSeq};
753 fn square(n: uint) -> uint { n * n }
755 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
759 // Test on-stack from_fn.
760 let mut v = Vec::from_fn(3u, square);
762 let v = v.as_slice();
763 assert_eq!(v.len(), 3u);
764 assert_eq!(v[0], 0u);
765 assert_eq!(v[1], 1u);
766 assert_eq!(v[2], 4u);
769 // Test on-heap from_fn.
770 v = Vec::from_fn(5u, square);
772 let v = v.as_slice();
773 assert_eq!(v.len(), 5u);
774 assert_eq!(v[0], 0u);
775 assert_eq!(v[1], 1u);
776 assert_eq!(v[2], 4u);
777 assert_eq!(v[3], 9u);
778 assert_eq!(v[4], 16u);
783 fn test_from_elem() {
784 // Test on-stack from_elem.
785 let mut v = Vec::from_elem(2u, 10u);
787 let v = v.as_slice();
788 assert_eq!(v.len(), 2u);
789 assert_eq!(v[0], 10u);
790 assert_eq!(v[1], 10u);
793 // Test on-heap from_elem.
794 v = Vec::from_elem(6u, 20u);
796 let v = v.as_slice();
797 assert_eq!(v[0], 20u);
798 assert_eq!(v[1], 20u);
799 assert_eq!(v[2], 20u);
800 assert_eq!(v[3], 20u);
801 assert_eq!(v[4], 20u);
802 assert_eq!(v[5], 20u);
808 let xs: [int, ..0] = [];
809 assert!(xs.is_empty());
810 assert!(![0i].is_empty());
814 fn test_len_divzero() {
817 let v1 : &[Z] = &[[]];
818 let v2 : &[Z] = &[[], []];
819 assert_eq!(mem::size_of::<Z>(), 0);
820 assert_eq!(v0.len(), 0);
821 assert_eq!(v1.len(), 1);
822 assert_eq!(v2.len(), 2);
827 let mut a = vec![11i];
828 assert_eq!(a.as_slice().get(1), None);
830 assert_eq!(a.as_slice().get(1).unwrap(), &12);
831 a = vec![11i, 12, 13];
832 assert_eq!(a.as_slice().get(1).unwrap(), &12);
838 assert_eq!(a.as_slice().head(), None);
840 assert_eq!(a.as_slice().head().unwrap(), &11);
842 assert_eq!(a.as_slice().head().unwrap(), &11);
847 let mut a = vec![11i];
848 assert_eq!(a.tail(), &[]);
850 assert_eq!(a.tail(), &[12]);
855 fn test_tail_empty() {
856 let a: Vec<int> = vec![];
862 let mut a = vec![11i, 12, 13];
863 assert_eq!(a.tailn(0), &[11, 12, 13]);
864 a = vec![11i, 12, 13];
865 assert_eq!(a.tailn(2), &[13]);
870 fn test_tailn_empty() {
871 let a: Vec<int> = vec![];
877 let mut a = vec![11i];
878 assert_eq!(a.init(), &[]);
880 assert_eq!(a.init(), &[11]);
885 fn test_init_empty() {
886 let a: Vec<int> = vec![];
892 let mut a = vec![11i, 12, 13];
893 assert_eq!(a.as_slice().initn(0), &[11, 12, 13]);
894 a = vec![11i, 12, 13];
895 assert_eq!(a.as_slice().initn(2), &[11]);
900 fn test_initn_empty() {
901 let a: Vec<int> = vec![];
902 a.as_slice().initn(2);
908 assert_eq!(a.as_slice().last(), None);
910 assert_eq!(a.as_slice().last().unwrap(), &11);
912 assert_eq!(a.as_slice().last().unwrap(), &12);
917 // Test fixed length vector.
918 let vec_fixed = [1i, 2, 3, 4];
919 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_vec();
920 assert_eq!(v_a.len(), 3u);
921 let v_a = v_a.as_slice();
922 assert_eq!(v_a[0], 2);
923 assert_eq!(v_a[1], 3);
924 assert_eq!(v_a[2], 4);
927 let vec_stack = &[1i, 2, 3];
928 let v_b = vec_stack.slice(1u, 3u).to_vec();
929 assert_eq!(v_b.len(), 2u);
930 let v_b = v_b.as_slice();
931 assert_eq!(v_b[0], 2);
932 assert_eq!(v_b[1], 3);
935 let vec_unique = vec![1i, 2, 3, 4, 5, 6];
936 let v_d = vec_unique.slice(1u, 6u).to_vec();
937 assert_eq!(v_d.len(), 5u);
938 let v_d = v_d.as_slice();
939 assert_eq!(v_d[0], 2);
940 assert_eq!(v_d[1], 3);
941 assert_eq!(v_d[2], 4);
942 assert_eq!(v_d[3], 5);
943 assert_eq!(v_d[4], 6);
947 fn test_slice_from() {
948 let vec = &[1i, 2, 3, 4];
949 assert_eq!(vec.slice_from(0), vec);
950 assert_eq!(vec.slice_from(2), &[3, 4]);
951 assert_eq!(vec.slice_from(4), &[]);
956 let vec = &[1i, 2, 3, 4];
957 assert_eq!(vec.slice_to(4), vec);
958 assert_eq!(vec.slice_to(2), &[1, 2]);
959 assert_eq!(vec.slice_to(0), &[]);
965 let mut v = vec![5i];
967 assert_eq!(v.len(), 0);
968 assert_eq!(e, Some(5));
976 fn test_swap_remove() {
977 let mut v = vec![1i, 2, 3, 4, 5];
978 let mut e = v.swap_remove(0);
979 assert_eq!(e, Some(1));
980 assert_eq!(v, vec![5i, 2, 3, 4]);
981 e = v.swap_remove(3);
982 assert_eq!(e, Some(4));
983 assert_eq!(v, vec![5i, 2, 3]);
985 e = v.swap_remove(3);
987 assert_eq!(v, vec![5i, 2, 3]);
991 fn test_swap_remove_noncopyable() {
992 // Tests that we don't accidentally run destructors twice.
993 let mut v = vec![rt::exclusive::Exclusive::new(()),
994 rt::exclusive::Exclusive::new(()),
995 rt::exclusive::Exclusive::new(())];
996 let mut _e = v.swap_remove(0);
997 assert_eq!(v.len(), 2);
998 _e = v.swap_remove(1);
999 assert_eq!(v.len(), 1);
1000 _e = v.swap_remove(0);
1001 assert_eq!(v.len(), 0);
1006 // Test on-stack push().
1009 assert_eq!(v.len(), 1u);
1010 assert_eq!(v.as_slice()[0], 1);
1012 // Test on-heap push().
1014 assert_eq!(v.len(), 2u);
1015 assert_eq!(v.as_slice()[0], 1);
1016 assert_eq!(v.as_slice()[1], 2);
1021 // Test on-stack grow().
1025 let v = v.as_slice();
1026 assert_eq!(v.len(), 2u);
1027 assert_eq!(v[0], 1);
1028 assert_eq!(v[1], 1);
1031 // Test on-heap grow().
1034 let v = v.as_slice();
1035 assert_eq!(v.len(), 5u);
1036 assert_eq!(v[0], 1);
1037 assert_eq!(v[1], 1);
1038 assert_eq!(v[2], 2);
1039 assert_eq!(v[3], 2);
1040 assert_eq!(v[4], 2);
1047 v.grow_fn(3u, square);
1048 let v = v.as_slice();
1049 assert_eq!(v.len(), 3u);
1050 assert_eq!(v[0], 0u);
1051 assert_eq!(v[1], 1u);
1052 assert_eq!(v[2], 4u);
1056 fn test_grow_set() {
1057 let mut v = vec![1i, 2, 3];
1058 v.grow_set(4u, &4, 5);
1059 let v = v.as_slice();
1060 assert_eq!(v.len(), 5u);
1061 assert_eq!(v[0], 1);
1062 assert_eq!(v[1], 2);
1063 assert_eq!(v[2], 3);
1064 assert_eq!(v[3], 4);
1065 assert_eq!(v[4], 5);
1069 fn test_truncate() {
1070 let mut v = vec![box 6i,box 5,box 4];
1072 let v = v.as_slice();
1073 assert_eq!(v.len(), 1);
1074 assert_eq!(*(v[0]), 6);
1075 // If the unsafe block didn't drop things properly, we blow up here.
1080 let mut v = vec![box 6i,box 5,box 4];
1082 assert_eq!(v.len(), 0);
1083 // If the unsafe block didn't drop things properly, we blow up here.
1088 fn case(a: Vec<uint>, b: Vec<uint>) {
1093 case(vec![], vec![]);
1094 case(vec![1u], vec![1]);
1095 case(vec![1u,1], vec![1]);
1096 case(vec![1u,2,3], vec![1,2,3]);
1097 case(vec![1u,1,2,3], vec![1,2,3]);
1098 case(vec![1u,2,2,3], vec![1,2,3]);
1099 case(vec![1u,2,3,3], vec![1,2,3]);
1100 case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1104 fn test_dedup_unique() {
1105 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1107 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1109 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1112 * If the boxed pointers were leaked or otherwise misused, valgrind
1113 * and/or rustrt should raise errors.
1118 fn test_dedup_shared() {
1119 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1121 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1123 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1126 * If the pointers were leaked or otherwise misused, valgrind and/or
1127 * rustrt should raise errors.
1133 let mut v = vec![1u, 2, 3, 4, 5];
1135 assert_eq!(v, vec![1u, 3, 5]);
1139 fn test_element_swaps() {
1140 let mut v = [1i, 2, 3];
1141 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1144 0 => assert!(v == [1, 3, 2]),
1145 1 => assert!(v == [3, 1, 2]),
1146 2 => assert!(v == [3, 2, 1]),
1147 3 => assert!(v == [2, 3, 1]),
1148 4 => assert!(v == [2, 1, 3]),
1149 5 => assert!(v == [1, 2, 3]),
1156 fn test_permutations() {
1158 let v: [int, ..0] = [];
1159 let mut it = v.permutations();
1160 let (min_size, max_opt) = it.size_hint();
1161 assert_eq!(min_size, 1);
1162 assert_eq!(max_opt.unwrap(), 1);
1163 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1164 assert_eq!(it.next(), None);
1167 let v = ["Hello".to_string()];
1168 let mut it = v.permutations();
1169 let (min_size, max_opt) = it.size_hint();
1170 assert_eq!(min_size, 1);
1171 assert_eq!(max_opt.unwrap(), 1);
1172 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1173 assert_eq!(it.next(), None);
1177 let mut it = v.permutations();
1178 let (min_size, max_opt) = it.size_hint();
1179 assert_eq!(min_size, 3*2);
1180 assert_eq!(max_opt.unwrap(), 3*2);
1181 assert_eq!(it.next(), Some(vec![1,2,3]));
1182 assert_eq!(it.next(), Some(vec![1,3,2]));
1183 assert_eq!(it.next(), Some(vec![3,1,2]));
1184 let (min_size, max_opt) = it.size_hint();
1185 assert_eq!(min_size, 3);
1186 assert_eq!(max_opt.unwrap(), 3);
1187 assert_eq!(it.next(), Some(vec![3,2,1]));
1188 assert_eq!(it.next(), Some(vec![2,3,1]));
1189 assert_eq!(it.next(), Some(vec![2,1,3]));
1190 assert_eq!(it.next(), None);
1193 // check that we have N! permutations
1194 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1196 let mut it = v.permutations();
1197 let (min_size, max_opt) = it.size_hint();
1201 assert_eq!(amt, it.swaps.swaps_made);
1202 assert_eq!(amt, min_size);
1203 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1204 assert_eq!(amt, max_opt.unwrap());
1209 fn test_lexicographic_permutations() {
1210 let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1211 assert!(v.prev_permutation() == false);
1212 assert!(v.next_permutation());
1213 assert_eq!(v, &mut[1, 2, 3, 5, 4]);
1214 assert!(v.prev_permutation());
1215 assert_eq!(v, &mut[1, 2, 3, 4, 5]);
1216 assert!(v.next_permutation());
1217 assert!(v.next_permutation());
1218 assert_eq!(v, &mut[1, 2, 4, 3, 5]);
1219 assert!(v.next_permutation());
1220 assert_eq!(v, &mut[1, 2, 4, 5, 3]);
1222 let v : &mut[int] = &mut[1i, 0, 0, 0];
1223 assert!(v.next_permutation() == false);
1224 assert!(v.prev_permutation());
1225 assert_eq!(v, &mut[0, 1, 0, 0]);
1226 assert!(v.prev_permutation());
1227 assert_eq!(v, &mut[0, 0, 1, 0]);
1228 assert!(v.prev_permutation());
1229 assert_eq!(v, &mut[0, 0, 0, 1]);
1230 assert!(v.prev_permutation() == false);
1234 fn test_lexicographic_permutations_empty_and_short() {
1235 let empty : &mut[int] = &mut[];
1236 assert!(empty.next_permutation() == false);
1237 assert_eq!(empty, &mut[]);
1238 assert!(empty.prev_permutation() == false);
1239 assert_eq!(empty, &mut[]);
1241 let one_elem : &mut[int] = &mut[4i];
1242 assert!(one_elem.prev_permutation() == false);
1243 assert_eq!(one_elem, &mut[4]);
1244 assert!(one_elem.next_permutation() == false);
1245 assert_eq!(one_elem, &mut[4]);
1247 let two_elem : &mut[int] = &mut[1i, 2];
1248 assert!(two_elem.prev_permutation() == false);
1249 assert_eq!(two_elem, &mut[1, 2]);
1250 assert!(two_elem.next_permutation());
1251 assert_eq!(two_elem, &mut[2, 1]);
1252 assert!(two_elem.next_permutation() == false);
1253 assert_eq!(two_elem, &mut[2, 1]);
1254 assert!(two_elem.prev_permutation());
1255 assert_eq!(two_elem, &mut[1, 2]);
1256 assert!(two_elem.prev_permutation() == false);
1257 assert_eq!(two_elem, &mut[1, 2]);
1261 fn test_position_elem() {
1262 assert!([].position_elem(&1i).is_none());
1264 let v1 = vec![1i, 2, 3, 3, 2, 5];
1265 assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
1266 assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
1267 assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
1268 assert!(v1.as_slice().position_elem(&4).is_none());
1272 fn test_bsearch_elem() {
1273 assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
1274 assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
1275 assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
1276 assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
1277 assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
1279 assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
1280 assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
1281 assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
1282 assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
1284 assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
1285 assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
1286 assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
1287 assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
1289 assert_eq!([2i,4,6].bsearch_elem(&1), None);
1290 assert_eq!([2i,4,6].bsearch_elem(&5), None);
1291 assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
1292 assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
1294 assert_eq!([2i,4].bsearch_elem(&1), None);
1295 assert_eq!([2i,4].bsearch_elem(&5), None);
1296 assert_eq!([2i,4].bsearch_elem(&2), Some(0));
1297 assert_eq!([2i,4].bsearch_elem(&4), Some(1));
1299 assert_eq!([2i].bsearch_elem(&1), None);
1300 assert_eq!([2i].bsearch_elem(&5), None);
1301 assert_eq!([2i].bsearch_elem(&2), Some(0));
1303 assert_eq!([].bsearch_elem(&1i), None);
1304 assert_eq!([].bsearch_elem(&5i), None);
1306 assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
1307 assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
1308 assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
1309 assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
1310 assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
1312 assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
1313 assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
1318 let mut v: Vec<int> = vec![10i, 20];
1319 assert_eq!(*v.get(0), 10);
1320 assert_eq!(*v.get(1), 20);
1322 assert_eq!(*v.get(0), 20);
1323 assert_eq!(*v.get(1), 10);
1325 let mut v3: Vec<int> = vec![];
1327 assert!(v3.is_empty());
1332 for len in range(4u, 25) {
1333 for _ in range(0i, 100) {
1334 let mut v = task_rng().gen_iter::<uint>().take(len)
1335 .collect::<Vec<uint>>();
1336 let mut v1 = v.clone();
1338 v.as_mut_slice().sort();
1339 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1341 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1342 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1344 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1345 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1349 // shouldn't fail/crash
1350 let mut v: [uint, .. 0] = [];
1353 let mut v = [0xDEADBEEFu];
1355 assert!(v == [0xDEADBEEF]);
1359 fn test_sort_stability() {
1360 for len in range(4i, 25) {
1361 for _ in range(0u, 10) {
1362 let mut counts = [0i, .. 10];
1364 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1365 // where the first item of each tuple is random, but
1366 // the second item represents which occurrence of that
1367 // number this element is, i.e. the second elements
1368 // will occur in sorted order.
1369 let mut v = range(0, len).map(|_| {
1370 let n = task_rng().gen::<uint>() % 10;
1373 }).collect::<Vec<(uint, int)>>();
1375 // only sort on the first element, so an unstable sort
1376 // may mix up the counts.
1377 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1379 // this comparison includes the count (the second item
1380 // of the tuple), so elements with equal first items
1381 // will need to be ordered with increasing
1382 // counts... i.e. exactly asserting that this sort is
1384 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1390 fn test_partition() {
1391 assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
1392 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1393 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1394 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1398 fn test_partitioned() {
1399 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
1400 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1401 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1402 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1407 let v: [Vec<int>, ..0] = [];
1408 assert_eq!(v.concat_vec(), vec![]);
1409 assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
1411 assert_eq!([&[1i], &[2i,3i]].concat_vec(), vec![1, 2, 3]);
1416 let v: [Vec<int>, ..0] = [];
1417 assert_eq!(v.connect_vec(&0), vec![]);
1418 assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1419 assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1421 assert_eq!([&[1i], &[2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1422 assert_eq!([&[1i], &[2i], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1427 let mut x = vec![1i, 2, 3];
1428 assert_eq!(x.shift(), Some(1));
1429 assert_eq!(&x, &vec![2i, 3]);
1430 assert_eq!(x.shift(), Some(2));
1431 assert_eq!(x.shift(), Some(3));
1432 assert_eq!(x.shift(), None);
1433 assert_eq!(x.len(), 0);
1438 let mut x = vec![1i, 2, 3];
1440 assert_eq!(x, vec![0, 1, 2, 3]);
1445 let mut a = vec![1i, 2, 4];
1447 assert_eq!(a, vec![1, 2, 3, 4]);
1449 let mut a = vec![1i, 2, 3];
1451 assert_eq!(a, vec![0, 1, 2, 3]);
1453 let mut a = vec![1i, 2, 3];
1455 assert_eq!(a, vec![1, 2, 3, 4]);
1459 assert_eq!(a, vec![1]);
1464 fn test_insert_oob() {
1465 let mut a = vec![1i, 2, 3];
1471 let mut a = vec![1i,2,3,4];
1473 assert_eq!(a.remove(2), Some(3));
1474 assert_eq!(a, vec![1i,2,4]);
1476 assert_eq!(a.remove(2), Some(4));
1477 assert_eq!(a, vec![1i,2]);
1479 assert_eq!(a.remove(2), None);
1480 assert_eq!(a, vec![1i,2]);
1482 assert_eq!(a.remove(0), Some(1));
1483 assert_eq!(a, vec![2i]);
1485 assert_eq!(a.remove(0), Some(2));
1486 assert_eq!(a, vec![]);
1488 assert_eq!(a.remove(0), None);
1489 assert_eq!(a.remove(10), None);
1493 fn test_capacity() {
1494 let mut v = vec![0u64];
1495 v.reserve_exact(10u);
1496 assert_eq!(v.capacity(), 10u);
1497 let mut v = vec![0u32];
1498 v.reserve_exact(10u);
1499 assert_eq!(v.capacity(), 10u);
1504 let v = vec![1i, 2, 3, 4, 5];
1505 let v = v.slice(1u, 3u);
1506 assert_eq!(v.len(), 2u);
1507 assert_eq!(v[0], 2);
1508 assert_eq!(v[1], 3);
1514 fn test_from_fn_fail() {
1515 Vec::from_fn(100, |v| {
1516 if v == 50 { fail!() }
1523 fn test_from_elem_fail() {
1527 boxes: (Box<int>, Rc<int>)
1531 fn clone(&self) -> S {
1532 self.f.set(self.f.get() + 1);
1533 if self.f.get() == 10 { fail!() }
1534 S { f: self.f, boxes: self.boxes.clone() }
1538 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1539 let _ = Vec::from_elem(100, s);
1544 fn test_grow_fn_fail() {
1546 v.grow_fn(100, |i| {
1550 (box 0i, Rc::new(0i))
1556 fn test_permute_fail() {
1557 let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
1558 (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
1560 for _ in v.permutations() {
1570 fn test_copy_memory_oob() {
1572 let mut a = [1i, 2, 3, 4];
1573 let b = [1i, 2, 3, 4, 5];
1579 fn test_total_ord() {
1580 [1i, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
1581 [1i, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
1582 [1i, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
1583 [1i, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
1584 [2i, 2].cmp(& &[1, 2, 3, 4]) == Greater;
1588 fn test_iterator() {
1589 let xs = [1i, 2, 5, 10, 11];
1590 let mut it = xs.iter();
1591 assert_eq!(it.size_hint(), (5, Some(5)));
1592 assert_eq!(it.next().unwrap(), &1);
1593 assert_eq!(it.size_hint(), (4, Some(4)));
1594 assert_eq!(it.next().unwrap(), &2);
1595 assert_eq!(it.size_hint(), (3, Some(3)));
1596 assert_eq!(it.next().unwrap(), &5);
1597 assert_eq!(it.size_hint(), (2, Some(2)));
1598 assert_eq!(it.next().unwrap(), &10);
1599 assert_eq!(it.size_hint(), (1, Some(1)));
1600 assert_eq!(it.next().unwrap(), &11);
1601 assert_eq!(it.size_hint(), (0, Some(0)));
1602 assert!(it.next().is_none());
1606 fn test_random_access_iterator() {
1607 let xs = [1i, 2, 5, 10, 11];
1608 let mut it = xs.iter();
1610 assert_eq!(it.indexable(), 5);
1611 assert_eq!(it.idx(0).unwrap(), &1);
1612 assert_eq!(it.idx(2).unwrap(), &5);
1613 assert_eq!(it.idx(4).unwrap(), &11);
1614 assert!(it.idx(5).is_none());
1616 assert_eq!(it.next().unwrap(), &1);
1617 assert_eq!(it.indexable(), 4);
1618 assert_eq!(it.idx(0).unwrap(), &2);
1619 assert_eq!(it.idx(3).unwrap(), &11);
1620 assert!(it.idx(4).is_none());
1622 assert_eq!(it.next().unwrap(), &2);
1623 assert_eq!(it.indexable(), 3);
1624 assert_eq!(it.idx(1).unwrap(), &10);
1625 assert!(it.idx(3).is_none());
1627 assert_eq!(it.next().unwrap(), &5);
1628 assert_eq!(it.indexable(), 2);
1629 assert_eq!(it.idx(1).unwrap(), &11);
1631 assert_eq!(it.next().unwrap(), &10);
1632 assert_eq!(it.indexable(), 1);
1633 assert_eq!(it.idx(0).unwrap(), &11);
1634 assert!(it.idx(1).is_none());
1636 assert_eq!(it.next().unwrap(), &11);
1637 assert_eq!(it.indexable(), 0);
1638 assert!(it.idx(0).is_none());
1640 assert!(it.next().is_none());
1644 fn test_iter_size_hints() {
1645 let mut xs = [1i, 2, 5, 10, 11];
1646 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1647 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1651 fn test_iter_clone() {
1652 let xs = [1i, 2, 5];
1653 let mut it = xs.iter();
1655 let mut jt = it.clone();
1656 assert_eq!(it.next(), jt.next());
1657 assert_eq!(it.next(), jt.next());
1658 assert_eq!(it.next(), jt.next());
1662 fn test_mut_iterator() {
1663 let mut xs = [1i, 2, 3, 4, 5];
1664 for x in xs.mut_iter() {
1667 assert!(xs == [2, 3, 4, 5, 6])
1671 fn test_rev_iterator() {
1673 let xs = [1i, 2, 5, 10, 11];
1674 let ys = [11, 10, 5, 2, 1];
1676 for &x in xs.iter().rev() {
1677 assert_eq!(x, ys[i]);
1684 fn test_mut_rev_iterator() {
1685 let mut xs = [1u, 2, 3, 4, 5];
1686 for (i,x) in xs.mut_iter().rev().enumerate() {
1689 assert!(xs == [5, 5, 5, 5, 5])
1693 fn test_move_iterator() {
1694 let xs = vec![1u,2,3,4,5];
1695 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1699 fn test_move_rev_iterator() {
1700 let xs = vec![1u,2,3,4,5];
1701 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1705 fn test_splitator() {
1706 let xs = &[1i,2,3,4,5];
1708 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1709 &[&[1], &[3], &[5]]);
1710 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
1711 &[&[], &[2,3,4,5]]);
1712 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
1713 &[&[1,2,3,4], &[]]);
1714 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
1716 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
1717 &[&[], &[], &[], &[], &[], &[]]);
1719 let xs: &[int] = &[];
1720 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1724 fn test_splitnator() {
1725 let xs = &[1i,2,3,4,5];
1727 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1729 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1731 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1732 &[&[], &[], &[], &[4,5]]);
1734 let xs: &[int] = &[];
1735 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1739 fn test_rsplitator() {
1740 let xs = &[1i,2,3,4,5];
1742 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
1743 &[&[5], &[3], &[1]]);
1744 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
1745 &[&[2,3,4,5], &[]]);
1746 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
1747 &[&[], &[1,2,3,4]]);
1748 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
1751 let xs: &[int] = &[];
1752 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1756 fn test_rsplitnator() {
1757 let xs = &[1,2,3,4,5];
1759 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1761 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1763 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1764 &[&[], &[], &[], &[1,2]]);
1766 let xs: &[int] = &[];
1767 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1771 fn test_windowsator() {
1772 let v = &[1i,2,3,4];
1774 assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), &[&[1,2], &[2,3], &[3,4]]);
1775 assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[2,3,4]]);
1776 assert!(v.windows(6).next().is_none());
1781 fn test_windowsator_0() {
1782 let v = &[1i,2,3,4];
1783 let _it = v.windows(0);
1787 fn test_chunksator() {
1788 let v = &[1i,2,3,4,5];
1790 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2], &[3,4], &[5]]);
1791 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[4,5]]);
1792 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3,4,5]]);
1794 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), &[&[5i], &[3,4], &[1,2]]);
1795 let mut it = v.chunks(2);
1796 assert_eq!(it.indexable(), 3);
1797 assert_eq!(it.idx(0).unwrap(), &[1,2]);
1798 assert_eq!(it.idx(1).unwrap(), &[3,4]);
1799 assert_eq!(it.idx(2).unwrap(), &[5]);
1800 assert_eq!(it.idx(3), None);
1805 fn test_chunksator_0() {
1806 let v = &[1i,2,3,4];
1807 let _it = v.chunks(0);
1811 fn test_move_from() {
1812 let mut a = [1i,2,3,4,5];
1813 let b = vec![6i,7,8];
1814 assert_eq!(a.move_from(b, 0, 3), 3);
1815 assert!(a == [6i,7,8,4,5]);
1816 let mut a = [7i,2,8,1];
1817 let b = vec![3i,1,4,1,5,9];
1818 assert_eq!(a.move_from(b, 0, 6), 4);
1819 assert!(a == [3i,1,4,1]);
1820 let mut a = [1i,2,3,4];
1821 let b = vec![5i,6,7,8,9,0];
1822 assert_eq!(a.move_from(b, 2, 3), 1);
1823 assert!(a == [7i,2,3,4]);
1824 let mut a = [1i,2,3,4,5];
1825 let b = vec![5i,6,7,8,9,0];
1826 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1827 assert!(a == [1i,2,6,7,5]);
1831 fn test_copy_from() {
1832 let mut a = [1i,2,3,4,5];
1834 assert_eq!(a.copy_from(b), 3);
1835 assert!(a == [6i,7,8,4,5]);
1836 let mut c = [7i,2,8,1];
1837 let d = [3i,1,4,1,5,9];
1838 assert_eq!(c.copy_from(d), 4);
1839 assert!(c == [3i,1,4,1]);
1843 fn test_reverse_part() {
1844 let mut values = [1i,2,3,4,5];
1845 values.mut_slice(1, 4).reverse();
1846 assert!(values == [1,4,3,2,5]);
1851 macro_rules! test_show_vec(
1852 ($x:expr, $x_str:expr) => ({
1853 let (x, x_str) = ($x, $x_str);
1854 assert_eq!(format!("{}", x), x_str);
1855 assert_eq!(format!("{}", x.as_slice()), x_str);
1858 let empty: Vec<int> = vec![];
1859 test_show_vec!(empty, "[]".to_string());
1860 test_show_vec!(vec![1i], "[1]".to_string());
1861 test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
1862 test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
1863 "[[], [1], [1, 1]]".to_string());
1865 let empty_mut: &mut [int] = &mut[];
1866 test_show_vec!(empty_mut, "[]".to_string());
1867 test_show_vec!(&mut[1i], "[1]".to_string());
1868 test_show_vec!(&mut[1i, 2, 3], "[1, 2, 3]".to_string());
1869 test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
1870 "[[], [1], [1, 1]]".to_string());
1874 fn test_vec_default() {
1877 let v: $ty = Default::default();
1878 assert!(v.is_empty());
1887 fn test_bytes_set_memory() {
1888 use slice::bytes::MutableByteVector;
1889 let mut values = [1u8,2,3,4,5];
1890 values.mut_slice(0,5).set_memory(0xAB);
1891 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1892 values.mut_slice(2,4).set_memory(0xFF);
1893 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1898 fn test_overflow_does_not_cause_segfault() {
1900 v.reserve_exact(-1);
1907 fn test_overflow_does_not_cause_segfault_managed() {
1908 let mut v = vec![Rc::new(1i)];
1909 v.reserve_exact(-1);
1910 v.push(Rc::new(2i));
1914 fn test_mut_split_at() {
1915 let mut values = [1u8,2,3,4,5];
1917 let (left, right) = values.mut_split_at(2);
1918 assert!(left.slice(0, left.len()) == [1, 2]);
1919 for p in left.mut_iter() {
1923 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1924 for p in right.mut_iter() {
1929 assert!(values == [2, 3, 5, 6, 7]);
1932 #[deriving(Clone, PartialEq)]
1936 fn test_iter_zero_sized() {
1937 let mut v = vec![Foo, Foo, Foo];
1938 assert_eq!(v.len(), 3);
1947 for f in v.slice(1, 3).iter() {
1953 for f in v.mut_iter() {
1959 for f in v.move_iter() {
1963 assert_eq!(cnt, 11);
1965 let xs: [Foo, ..3] = [Foo, Foo, Foo];
1967 for f in xs.iter() {
1975 fn test_shrink_to_fit() {
1976 let mut xs = vec![0, 1, 2, 3];
1977 for i in range(4i, 100) {
1980 assert_eq!(xs.capacity(), 128);
1982 assert_eq!(xs.capacity(), 100);
1983 assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
1987 fn test_starts_with() {
1988 assert!(b"foobar".starts_with(b"foo"));
1989 assert!(!b"foobar".starts_with(b"oob"));
1990 assert!(!b"foobar".starts_with(b"bar"));
1991 assert!(!b"foo".starts_with(b"foobar"));
1992 assert!(!b"bar".starts_with(b"foobar"));
1993 assert!(b"foobar".starts_with(b"foobar"));
1994 let empty: &[u8] = [];
1995 assert!(empty.starts_with(empty));
1996 assert!(!empty.starts_with(b"foo"));
1997 assert!(b"foobar".starts_with(empty));
2001 fn test_ends_with() {
2002 assert!(b"foobar".ends_with(b"bar"));
2003 assert!(!b"foobar".ends_with(b"oba"));
2004 assert!(!b"foobar".ends_with(b"foo"));
2005 assert!(!b"foo".ends_with(b"foobar"));
2006 assert!(!b"bar".ends_with(b"foobar"));
2007 assert!(b"foobar".ends_with(b"foobar"));
2008 let empty: &[u8] = [];
2009 assert!(empty.ends_with(empty));
2010 assert!(!empty.ends_with(b"foo"));
2011 assert!(b"foobar".ends_with(empty));
2015 fn test_shift_ref() {
2016 let mut x: &[int] = [1, 2, 3, 4, 5];
2017 let h = x.shift_ref();
2018 assert_eq!(*h.unwrap(), 1);
2019 assert_eq!(x.len(), 4);
2020 assert_eq!(x[0], 2);
2021 assert_eq!(x[3], 5);
2023 let mut y: &[int] = [];
2024 assert_eq!(y.shift_ref(), None);
2029 let mut x: &[int] = [1, 2, 3, 4, 5];
2030 let h = x.pop_ref();
2031 assert_eq!(*h.unwrap(), 5);
2032 assert_eq!(x.len(), 4);
2033 assert_eq!(x[0], 1);
2034 assert_eq!(x[3], 4);
2036 let mut y: &[int] = [];
2037 assert!(y.pop_ref().is_none());
2041 fn test_mut_splitator() {
2042 let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2043 assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
2044 for slice in xs.mut_split(|x| *x == 0) {
2047 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2049 let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2050 for slice in xs.mut_split(|x| *x == 0).take(5) {
2053 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2057 fn test_mut_splitator_rev() {
2058 let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2059 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2062 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2067 let mut v = [0i,1,2];
2068 assert_eq!(v.get_mut(3), None);
2069 v.get_mut(1).map(|e| *e = 7);
2070 assert_eq!(v[1], 7);
2072 assert_eq!(v.get_mut(2), Some(&mut x));
2076 fn test_mut_chunks() {
2077 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2078 for (i, chunk) in v.mut_chunks(3).enumerate() {
2079 for x in chunk.mut_iter() {
2083 let result = [0u8, 0, 0, 1, 1, 1, 2];
2084 assert!(v == result);
2088 fn test_mut_chunks_rev() {
2089 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2090 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2091 for x in chunk.mut_iter() {
2095 let result = [2u8, 2, 2, 1, 1, 1, 0];
2096 assert!(v == result);
2101 fn test_mut_chunks_0() {
2102 let mut v = [1i, 2, 3, 4];
2103 let _it = v.mut_chunks(0);
2107 fn test_mut_shift_ref() {
2108 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2109 let h = x.mut_shift_ref();
2110 assert_eq!(*h.unwrap(), 1);
2111 assert_eq!(x.len(), 4);
2112 assert_eq!(x[0], 2);
2113 assert_eq!(x[3], 5);
2115 let mut y: &mut [int] = [];
2116 assert!(y.mut_shift_ref().is_none());
2120 fn test_mut_pop_ref() {
2121 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2122 let h = x.mut_pop_ref();
2123 assert_eq!(*h.unwrap(), 5);
2124 assert_eq!(x.len(), 4);
2125 assert_eq!(x[0], 1);
2126 assert_eq!(x[3], 4);
2128 let mut y: &mut [int] = [];
2129 assert!(y.mut_pop_ref().is_none());
2133 fn test_mut_last() {
2134 let mut x = [1i, 2, 3, 4, 5];
2135 let h = x.mut_last();
2136 assert_eq!(*h.unwrap(), 5);
2138 let y: &mut [int] = [];
2139 assert!(y.mut_last().is_none());
2145 use std::prelude::*;
2146 use std::rand::{weak_rng, Rng};
2155 fn iterator(b: &mut Bencher) {
2156 // peculiar numbers to stop LLVM from optimising the summation
2158 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2165 // sum == 11806, to stop dead code elimination.
2166 if sum == 0 {fail!()}
2171 fn mut_iterator(b: &mut Bencher) {
2172 let mut v = Vec::from_elem(100, 0i);
2176 for x in v.mut_iter() {
2184 fn concat(b: &mut Bencher) {
2185 let xss: Vec<Vec<uint>> =
2186 Vec::from_fn(100, |i| range(0u, i).collect());
2188 xss.as_slice().concat_vec()
2193 fn connect(b: &mut Bencher) {
2194 let xss: Vec<Vec<uint>> =
2195 Vec::from_fn(100, |i| range(0u, i).collect());
2197 xss.as_slice().connect_vec(&0)
2202 fn push(b: &mut Bencher) {
2203 let mut vec: Vec<uint> = vec![];
2211 fn starts_with_same_vector(b: &mut Bencher) {
2212 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2214 vec.as_slice().starts_with(vec.as_slice())
2219 fn starts_with_single_element(b: &mut Bencher) {
2220 let vec: Vec<uint> = vec![0];
2222 vec.as_slice().starts_with(vec.as_slice())
2227 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2228 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2229 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2232 vec.as_slice().starts_with(match_vec.as_slice())
2237 fn ends_with_same_vector(b: &mut Bencher) {
2238 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2240 vec.as_slice().ends_with(vec.as_slice())
2245 fn ends_with_single_element(b: &mut Bencher) {
2246 let vec: Vec<uint> = vec![0];
2248 vec.as_slice().ends_with(vec.as_slice())
2253 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2254 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2255 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2256 match_vec.as_mut_slice()[0] = 200;
2258 vec.as_slice().starts_with(match_vec.as_slice())
2263 fn contains_last_element(b: &mut Bencher) {
2264 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2271 fn zero_1kb_from_elem(b: &mut Bencher) {
2273 Vec::from_elem(1024, 0u8)
2278 fn zero_1kb_set_memory(b: &mut Bencher) {
2280 let mut v: Vec<uint> = Vec::with_capacity(1024);
2282 let vp = v.as_mut_ptr();
2283 ptr::set_memory(vp, 0, 1024);
2291 fn zero_1kb_loop_set(b: &mut Bencher) {
2293 let mut v: Vec<uint> = Vec::with_capacity(1024);
2297 for i in range(0u, 1024) {
2304 fn zero_1kb_mut_iter(b: &mut Bencher) {
2306 let mut v = Vec::with_capacity(1024);
2310 for x in v.mut_iter() {
2318 fn random_inserts(b: &mut Bencher) {
2319 let mut rng = weak_rng();
2321 let mut v = Vec::from_elem(30, (0u, 0u));
2322 for _ in range(0u, 100) {
2324 v.insert(rng.gen::<uint>() % (l + 1),
2330 fn random_removes(b: &mut Bencher) {
2331 let mut rng = weak_rng();
2333 let mut v = Vec::from_elem(130, (0u, 0u));
2334 for _ in range(0u, 100) {
2336 v.remove(rng.gen::<uint>() % l);
2342 fn sort_random_small(b: &mut Bencher) {
2343 let mut rng = weak_rng();
2345 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
2346 v.as_mut_slice().sort();
2348 b.bytes = 5 * mem::size_of::<u64>() as u64;
2352 fn sort_random_medium(b: &mut Bencher) {
2353 let mut rng = weak_rng();
2355 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
2356 v.as_mut_slice().sort();
2358 b.bytes = 100 * mem::size_of::<u64>() as u64;
2362 fn sort_random_large(b: &mut Bencher) {
2363 let mut rng = weak_rng();
2365 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
2366 v.as_mut_slice().sort();
2368 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2372 fn sort_sorted(b: &mut Bencher) {
2373 let mut v = Vec::from_fn(10000, |i| i);
2377 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2380 type BigSortable = (u64,u64,u64,u64);
2383 fn sort_big_random_small(b: &mut Bencher) {
2384 let mut rng = weak_rng();
2386 let mut v = rng.gen_iter::<BigSortable>().take(5)
2387 .collect::<Vec<BigSortable>>();
2390 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2394 fn sort_big_random_medium(b: &mut Bencher) {
2395 let mut rng = weak_rng();
2397 let mut v = rng.gen_iter::<BigSortable>().take(100)
2398 .collect::<Vec<BigSortable>>();
2401 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2405 fn sort_big_random_large(b: &mut Bencher) {
2406 let mut rng = weak_rng();
2408 let mut v = rng.gen_iter::<BigSortable>().take(10000)
2409 .collect::<Vec<BigSortable>>();
2412 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2416 fn sort_big_sorted(b: &mut Bencher) {
2417 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2421 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;