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, mut_ref_slice, 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 [_] = &mut [0i, 1, 2];
642 /// v.next_permutation();
643 /// let b: &mut [_] = &mut [0i, 2, 1];
645 /// v.next_permutation();
646 /// let b: &mut [_] = &mut [1i, 0, 2];
649 fn next_permutation(self) -> bool;
651 /// Mutates the slice to the previous lexicographic permutation.
653 /// Returns `true` if successful and `false` if the slice is at the
654 /// first-ordered permutation.
659 /// let v: &mut [_] = &mut [1i, 0, 2];
660 /// v.prev_permutation();
661 /// let b: &mut [_] = &mut [0i, 2, 1];
663 /// v.prev_permutation();
664 /// let b: &mut [_] = &mut [0i, 1, 2];
667 fn prev_permutation(self) -> bool;
670 impl<'a, T: Ord> MutableOrdSlice<T> for &'a mut [T] {
673 self.sort_by(|a,b| a.cmp(b))
676 fn next_permutation(self) -> bool {
677 // These cases only have 1 permutation each, so we can't do anything.
678 if self.len() < 2 { return false; }
680 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
681 let mut i = self.len() - 1;
682 while i > 0 && self[i-1] >= self[i] {
686 // If that is the entire vector, this is the last-ordered permutation.
691 // Step 2: Find the rightmost element larger than the pivot (i-1)
692 let mut j = self.len() - 1;
693 while j >= i && self[j] <= self[i-1] {
697 // Step 3: Swap that element with the pivot
700 // Step 4: Reverse the (previously) weakly decreasing part
701 self.mut_slice_from(i).reverse();
706 fn prev_permutation(self) -> bool {
707 // These cases only have 1 permutation each, so we can't do anything.
708 if self.len() < 2 { return false; }
710 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
711 let mut i = self.len() - 1;
712 while i > 0 && self[i-1] <= self[i] {
716 // If that is the entire vector, this is the first-ordered permutation.
721 // Step 2: Reverse the weakly increasing part
722 self.mut_slice_from(i).reverse();
724 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
725 let mut j = self.len() - 1;
726 while j >= i && self[j-1] < self[i-1] {
730 // Step 4: Swap that element with the pivot
737 /// Unsafe operations
739 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
740 pub use core::slice::raw::{shift_ptr, pop_ptr};
746 use std::default::Default;
749 use std::rand::{Rng, task_rng};
754 use {Mutable, MutableSeq};
757 fn square(n: uint) -> uint { n * n }
759 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
763 // Test on-stack from_fn.
764 let mut v = Vec::from_fn(3u, square);
766 let v = v.as_slice();
767 assert_eq!(v.len(), 3u);
768 assert_eq!(v[0], 0u);
769 assert_eq!(v[1], 1u);
770 assert_eq!(v[2], 4u);
773 // Test on-heap from_fn.
774 v = Vec::from_fn(5u, square);
776 let v = v.as_slice();
777 assert_eq!(v.len(), 5u);
778 assert_eq!(v[0], 0u);
779 assert_eq!(v[1], 1u);
780 assert_eq!(v[2], 4u);
781 assert_eq!(v[3], 9u);
782 assert_eq!(v[4], 16u);
787 fn test_from_elem() {
788 // Test on-stack from_elem.
789 let mut v = Vec::from_elem(2u, 10u);
791 let v = v.as_slice();
792 assert_eq!(v.len(), 2u);
793 assert_eq!(v[0], 10u);
794 assert_eq!(v[1], 10u);
797 // Test on-heap from_elem.
798 v = Vec::from_elem(6u, 20u);
800 let v = v.as_slice();
801 assert_eq!(v[0], 20u);
802 assert_eq!(v[1], 20u);
803 assert_eq!(v[2], 20u);
804 assert_eq!(v[3], 20u);
805 assert_eq!(v[4], 20u);
806 assert_eq!(v[5], 20u);
812 let xs: [int, ..0] = [];
813 assert!(xs.is_empty());
814 assert!(![0i].is_empty());
818 fn test_len_divzero() {
821 let v1 : &[Z] = &[[]];
822 let v2 : &[Z] = &[[], []];
823 assert_eq!(mem::size_of::<Z>(), 0);
824 assert_eq!(v0.len(), 0);
825 assert_eq!(v1.len(), 1);
826 assert_eq!(v2.len(), 2);
831 let mut a = vec![11i];
832 assert_eq!(a.as_slice().get(1), None);
834 assert_eq!(a.as_slice().get(1).unwrap(), &12);
835 a = vec![11i, 12, 13];
836 assert_eq!(a.as_slice().get(1).unwrap(), &12);
842 assert_eq!(a.as_slice().head(), None);
844 assert_eq!(a.as_slice().head().unwrap(), &11);
846 assert_eq!(a.as_slice().head().unwrap(), &11);
851 let mut a = vec![11i];
853 assert_eq!(a.tail(), b);
855 let b: &[int] = &[12];
856 assert_eq!(a.tail(), b);
861 fn test_tail_empty() {
862 let a: Vec<int> = vec![];
868 let mut a = vec![11i, 12, 13];
869 let b: &[int] = &[11, 12, 13];
870 assert_eq!(a.tailn(0), b);
871 a = vec![11i, 12, 13];
872 let b: &[int] = &[13];
873 assert_eq!(a.tailn(2), b);
878 fn test_tailn_empty() {
879 let a: Vec<int> = vec![];
885 let mut a = vec![11i];
887 assert_eq!(a.init(), b);
889 let b: &[int] = &[11];
890 assert_eq!(a.init(), b);
895 fn test_init_empty() {
896 let a: Vec<int> = vec![];
902 let mut a = vec![11i, 12, 13];
903 let b: &[int] = &[11, 12, 13];
904 assert_eq!(a.as_slice().initn(0), b);
905 a = vec![11i, 12, 13];
906 let b: &[int] = &[11];
907 assert_eq!(a.as_slice().initn(2), b);
912 fn test_initn_empty() {
913 let a: Vec<int> = vec![];
914 a.as_slice().initn(2);
920 assert_eq!(a.as_slice().last(), None);
922 assert_eq!(a.as_slice().last().unwrap(), &11);
924 assert_eq!(a.as_slice().last().unwrap(), &12);
929 // Test fixed length vector.
930 let vec_fixed = [1i, 2, 3, 4];
931 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_vec();
932 assert_eq!(v_a.len(), 3u);
933 let v_a = v_a.as_slice();
934 assert_eq!(v_a[0], 2);
935 assert_eq!(v_a[1], 3);
936 assert_eq!(v_a[2], 4);
939 let vec_stack = &[1i, 2, 3];
940 let v_b = vec_stack.slice(1u, 3u).to_vec();
941 assert_eq!(v_b.len(), 2u);
942 let v_b = v_b.as_slice();
943 assert_eq!(v_b[0], 2);
944 assert_eq!(v_b[1], 3);
947 let vec_unique = vec![1i, 2, 3, 4, 5, 6];
948 let v_d = vec_unique.slice(1u, 6u).to_vec();
949 assert_eq!(v_d.len(), 5u);
950 let v_d = v_d.as_slice();
951 assert_eq!(v_d[0], 2);
952 assert_eq!(v_d[1], 3);
953 assert_eq!(v_d[2], 4);
954 assert_eq!(v_d[3], 5);
955 assert_eq!(v_d[4], 6);
959 fn test_slice_from() {
960 let vec: &[int] = &[1, 2, 3, 4];
961 assert_eq!(vec.slice_from(0), vec);
962 let b: &[int] = &[3, 4];
963 assert_eq!(vec.slice_from(2), b);
965 assert_eq!(vec.slice_from(4), b);
970 let vec: &[int] = &[1, 2, 3, 4];
971 assert_eq!(vec.slice_to(4), vec);
972 let b: &[int] = &[1, 2];
973 assert_eq!(vec.slice_to(2), b);
975 assert_eq!(vec.slice_to(0), b);
981 let mut v = vec![5i];
983 assert_eq!(v.len(), 0);
984 assert_eq!(e, Some(5));
992 fn test_swap_remove() {
993 let mut v = vec![1i, 2, 3, 4, 5];
994 let mut e = v.swap_remove(0);
995 assert_eq!(e, Some(1));
996 assert_eq!(v, vec![5i, 2, 3, 4]);
997 e = v.swap_remove(3);
998 assert_eq!(e, Some(4));
999 assert_eq!(v, vec![5i, 2, 3]);
1001 e = v.swap_remove(3);
1002 assert_eq!(e, None);
1003 assert_eq!(v, vec![5i, 2, 3]);
1007 fn test_swap_remove_noncopyable() {
1008 // Tests that we don't accidentally run destructors twice.
1009 let mut v = vec![rt::exclusive::Exclusive::new(()),
1010 rt::exclusive::Exclusive::new(()),
1011 rt::exclusive::Exclusive::new(())];
1012 let mut _e = v.swap_remove(0);
1013 assert_eq!(v.len(), 2);
1014 _e = v.swap_remove(1);
1015 assert_eq!(v.len(), 1);
1016 _e = v.swap_remove(0);
1017 assert_eq!(v.len(), 0);
1022 // Test on-stack push().
1025 assert_eq!(v.len(), 1u);
1026 assert_eq!(v.as_slice()[0], 1);
1028 // Test on-heap push().
1030 assert_eq!(v.len(), 2u);
1031 assert_eq!(v.as_slice()[0], 1);
1032 assert_eq!(v.as_slice()[1], 2);
1037 // Test on-stack grow().
1041 let v = v.as_slice();
1042 assert_eq!(v.len(), 2u);
1043 assert_eq!(v[0], 1);
1044 assert_eq!(v[1], 1);
1047 // Test on-heap grow().
1050 let v = v.as_slice();
1051 assert_eq!(v.len(), 5u);
1052 assert_eq!(v[0], 1);
1053 assert_eq!(v[1], 1);
1054 assert_eq!(v[2], 2);
1055 assert_eq!(v[3], 2);
1056 assert_eq!(v[4], 2);
1063 v.grow_fn(3u, square);
1064 let v = v.as_slice();
1065 assert_eq!(v.len(), 3u);
1066 assert_eq!(v[0], 0u);
1067 assert_eq!(v[1], 1u);
1068 assert_eq!(v[2], 4u);
1072 fn test_grow_set() {
1073 let mut v = vec![1i, 2, 3];
1074 v.grow_set(4u, &4, 5);
1075 let v = v.as_slice();
1076 assert_eq!(v.len(), 5u);
1077 assert_eq!(v[0], 1);
1078 assert_eq!(v[1], 2);
1079 assert_eq!(v[2], 3);
1080 assert_eq!(v[3], 4);
1081 assert_eq!(v[4], 5);
1085 fn test_truncate() {
1086 let mut v = vec![box 6i,box 5,box 4];
1088 let v = v.as_slice();
1089 assert_eq!(v.len(), 1);
1090 assert_eq!(*(v[0]), 6);
1091 // If the unsafe block didn't drop things properly, we blow up here.
1096 let mut v = vec![box 6i,box 5,box 4];
1098 assert_eq!(v.len(), 0);
1099 // If the unsafe block didn't drop things properly, we blow up here.
1104 fn case(a: Vec<uint>, b: Vec<uint>) {
1109 case(vec![], vec![]);
1110 case(vec![1u], vec![1]);
1111 case(vec![1u,1], vec![1]);
1112 case(vec![1u,2,3], vec![1,2,3]);
1113 case(vec![1u,1,2,3], vec![1,2,3]);
1114 case(vec![1u,2,2,3], vec![1,2,3]);
1115 case(vec![1u,2,3,3], vec![1,2,3]);
1116 case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1120 fn test_dedup_unique() {
1121 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1123 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1125 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1128 * If the boxed pointers were leaked or otherwise misused, valgrind
1129 * and/or rustrt should raise errors.
1134 fn test_dedup_shared() {
1135 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1137 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1139 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1142 * If the pointers were leaked or otherwise misused, valgrind and/or
1143 * rustrt should raise errors.
1149 let mut v = vec![1u, 2, 3, 4, 5];
1151 assert_eq!(v, vec![1u, 3, 5]);
1155 fn test_element_swaps() {
1156 let mut v = [1i, 2, 3];
1157 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1160 0 => assert!(v == [1, 3, 2]),
1161 1 => assert!(v == [3, 1, 2]),
1162 2 => assert!(v == [3, 2, 1]),
1163 3 => assert!(v == [2, 3, 1]),
1164 4 => assert!(v == [2, 1, 3]),
1165 5 => assert!(v == [1, 2, 3]),
1172 fn test_permutations() {
1174 let v: [int, ..0] = [];
1175 let mut it = v.permutations();
1176 let (min_size, max_opt) = it.size_hint();
1177 assert_eq!(min_size, 1);
1178 assert_eq!(max_opt.unwrap(), 1);
1179 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1180 assert_eq!(it.next(), None);
1183 let v = ["Hello".to_string()];
1184 let mut it = v.permutations();
1185 let (min_size, max_opt) = it.size_hint();
1186 assert_eq!(min_size, 1);
1187 assert_eq!(max_opt.unwrap(), 1);
1188 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1189 assert_eq!(it.next(), None);
1193 let mut it = v.permutations();
1194 let (min_size, max_opt) = it.size_hint();
1195 assert_eq!(min_size, 3*2);
1196 assert_eq!(max_opt.unwrap(), 3*2);
1197 assert_eq!(it.next(), Some(vec![1,2,3]));
1198 assert_eq!(it.next(), Some(vec![1,3,2]));
1199 assert_eq!(it.next(), Some(vec![3,1,2]));
1200 let (min_size, max_opt) = it.size_hint();
1201 assert_eq!(min_size, 3);
1202 assert_eq!(max_opt.unwrap(), 3);
1203 assert_eq!(it.next(), Some(vec![3,2,1]));
1204 assert_eq!(it.next(), Some(vec![2,3,1]));
1205 assert_eq!(it.next(), Some(vec![2,1,3]));
1206 assert_eq!(it.next(), None);
1209 // check that we have N! permutations
1210 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1212 let mut it = v.permutations();
1213 let (min_size, max_opt) = it.size_hint();
1217 assert_eq!(amt, it.swaps.swaps_made);
1218 assert_eq!(amt, min_size);
1219 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1220 assert_eq!(amt, max_opt.unwrap());
1225 fn test_lexicographic_permutations() {
1226 let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1227 assert!(v.prev_permutation() == false);
1228 assert!(v.next_permutation());
1229 let b: &mut[int] = &mut[1, 2, 3, 5, 4];
1231 assert!(v.prev_permutation());
1232 let b: &mut[int] = &mut[1, 2, 3, 4, 5];
1234 assert!(v.next_permutation());
1235 assert!(v.next_permutation());
1236 let b: &mut[int] = &mut[1, 2, 4, 3, 5];
1238 assert!(v.next_permutation());
1239 let b: &mut[int] = &mut[1, 2, 4, 5, 3];
1242 let v : &mut[int] = &mut[1i, 0, 0, 0];
1243 assert!(v.next_permutation() == false);
1244 assert!(v.prev_permutation());
1245 let b: &mut[int] = &mut[0, 1, 0, 0];
1247 assert!(v.prev_permutation());
1248 let b: &mut[int] = &mut[0, 0, 1, 0];
1250 assert!(v.prev_permutation());
1251 let b: &mut[int] = &mut[0, 0, 0, 1];
1253 assert!(v.prev_permutation() == false);
1257 fn test_lexicographic_permutations_empty_and_short() {
1258 let empty : &mut[int] = &mut[];
1259 assert!(empty.next_permutation() == false);
1260 let b: &mut[int] = &mut[];
1261 assert!(empty == b);
1262 assert!(empty.prev_permutation() == false);
1263 assert!(empty == b);
1265 let one_elem : &mut[int] = &mut[4i];
1266 assert!(one_elem.prev_permutation() == false);
1267 let b: &mut[int] = &mut[4];
1268 assert!(one_elem == b);
1269 assert!(one_elem.next_permutation() == false);
1270 assert!(one_elem == b);
1272 let two_elem : &mut[int] = &mut[1i, 2];
1273 assert!(two_elem.prev_permutation() == false);
1274 let b : &mut[int] = &mut[1, 2];
1275 let c : &mut[int] = &mut[2, 1];
1276 assert!(two_elem == b);
1277 assert!(two_elem.next_permutation());
1278 assert!(two_elem == c);
1279 assert!(two_elem.next_permutation() == false);
1280 assert!(two_elem == c);
1281 assert!(two_elem.prev_permutation());
1282 assert!(two_elem == b);
1283 assert!(two_elem.prev_permutation() == false);
1284 assert!(two_elem == b);
1288 fn test_position_elem() {
1289 assert!([].position_elem(&1i).is_none());
1291 let v1 = vec![1i, 2, 3, 3, 2, 5];
1292 assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
1293 assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
1294 assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
1295 assert!(v1.as_slice().position_elem(&4).is_none());
1299 fn test_bsearch_elem() {
1300 assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
1301 assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
1302 assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
1303 assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
1304 assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
1306 assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
1307 assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
1308 assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
1309 assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
1311 assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
1312 assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
1313 assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
1314 assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
1316 assert_eq!([2i,4,6].bsearch_elem(&1), None);
1317 assert_eq!([2i,4,6].bsearch_elem(&5), None);
1318 assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
1319 assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
1321 assert_eq!([2i,4].bsearch_elem(&1), None);
1322 assert_eq!([2i,4].bsearch_elem(&5), None);
1323 assert_eq!([2i,4].bsearch_elem(&2), Some(0));
1324 assert_eq!([2i,4].bsearch_elem(&4), Some(1));
1326 assert_eq!([2i].bsearch_elem(&1), None);
1327 assert_eq!([2i].bsearch_elem(&5), None);
1328 assert_eq!([2i].bsearch_elem(&2), Some(0));
1330 assert_eq!([].bsearch_elem(&1i), None);
1331 assert_eq!([].bsearch_elem(&5i), None);
1333 assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
1334 assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
1335 assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
1336 assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
1337 assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
1339 assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
1340 assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
1345 let mut v: Vec<int> = vec![10i, 20];
1346 assert_eq!(*v.get(0), 10);
1347 assert_eq!(*v.get(1), 20);
1349 assert_eq!(*v.get(0), 20);
1350 assert_eq!(*v.get(1), 10);
1352 let mut v3: Vec<int> = vec![];
1354 assert!(v3.is_empty());
1359 for len in range(4u, 25) {
1360 for _ in range(0i, 100) {
1361 let mut v = task_rng().gen_iter::<uint>().take(len)
1362 .collect::<Vec<uint>>();
1363 let mut v1 = v.clone();
1365 v.as_mut_slice().sort();
1366 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1368 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1369 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1371 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1372 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1376 // shouldn't fail/crash
1377 let mut v: [uint, .. 0] = [];
1380 let mut v = [0xDEADBEEFu];
1382 assert!(v == [0xDEADBEEF]);
1386 fn test_sort_stability() {
1387 for len in range(4i, 25) {
1388 for _ in range(0u, 10) {
1389 let mut counts = [0i, .. 10];
1391 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1392 // where the first item of each tuple is random, but
1393 // the second item represents which occurrence of that
1394 // number this element is, i.e. the second elements
1395 // will occur in sorted order.
1396 let mut v = range(0, len).map(|_| {
1397 let n = task_rng().gen::<uint>() % 10;
1400 }).collect::<Vec<(uint, int)>>();
1402 // only sort on the first element, so an unstable sort
1403 // may mix up the counts.
1404 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1406 // this comparison includes the count (the second item
1407 // of the tuple), so elements with equal first items
1408 // will need to be ordered with increasing
1409 // counts... i.e. exactly asserting that this sort is
1411 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1417 fn test_partition() {
1418 assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
1419 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1420 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1421 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1425 fn test_partitioned() {
1426 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
1427 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1428 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1429 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1434 let v: [Vec<int>, ..0] = [];
1435 assert_eq!(v.concat_vec(), vec![]);
1436 assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
1438 let v: [&[int], ..2] = [&[1], &[2, 3]];
1439 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
1440 let v: [&[int], ..3] = [&[1], &[2], &[3]];
1441 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
1446 let v: [Vec<int>, ..0] = [];
1447 assert_eq!(v.connect_vec(&0), vec![]);
1448 assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1449 assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1451 let v: [&[int], ..2] = [&[1], &[2, 3]];
1452 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
1453 let v: [&[int], ..3] = [&[1], &[2], &[3]];
1454 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
1459 let mut x = vec![1i, 2, 3];
1460 assert_eq!(x.shift(), Some(1));
1461 assert_eq!(&x, &vec![2i, 3]);
1462 assert_eq!(x.shift(), Some(2));
1463 assert_eq!(x.shift(), Some(3));
1464 assert_eq!(x.shift(), None);
1465 assert_eq!(x.len(), 0);
1470 let mut x = vec![1i, 2, 3];
1472 assert_eq!(x, vec![0, 1, 2, 3]);
1477 let mut a = vec![1i, 2, 4];
1479 assert_eq!(a, vec![1, 2, 3, 4]);
1481 let mut a = vec![1i, 2, 3];
1483 assert_eq!(a, vec![0, 1, 2, 3]);
1485 let mut a = vec![1i, 2, 3];
1487 assert_eq!(a, vec![1, 2, 3, 4]);
1491 assert_eq!(a, vec![1]);
1496 fn test_insert_oob() {
1497 let mut a = vec![1i, 2, 3];
1503 let mut a = vec![1i,2,3,4];
1505 assert_eq!(a.remove(2), Some(3));
1506 assert_eq!(a, vec![1i,2,4]);
1508 assert_eq!(a.remove(2), Some(4));
1509 assert_eq!(a, vec![1i,2]);
1511 assert_eq!(a.remove(2), None);
1512 assert_eq!(a, vec![1i,2]);
1514 assert_eq!(a.remove(0), Some(1));
1515 assert_eq!(a, vec![2i]);
1517 assert_eq!(a.remove(0), Some(2));
1518 assert_eq!(a, vec![]);
1520 assert_eq!(a.remove(0), None);
1521 assert_eq!(a.remove(10), None);
1525 fn test_capacity() {
1526 let mut v = vec![0u64];
1527 v.reserve_exact(10u);
1528 assert_eq!(v.capacity(), 10u);
1529 let mut v = vec![0u32];
1530 v.reserve_exact(10u);
1531 assert_eq!(v.capacity(), 10u);
1536 let v = vec![1i, 2, 3, 4, 5];
1537 let v = v.slice(1u, 3u);
1538 assert_eq!(v.len(), 2u);
1539 assert_eq!(v[0], 2);
1540 assert_eq!(v[1], 3);
1546 fn test_from_fn_fail() {
1547 Vec::from_fn(100, |v| {
1548 if v == 50 { fail!() }
1555 fn test_from_elem_fail() {
1559 boxes: (Box<int>, Rc<int>)
1563 fn clone(&self) -> S {
1564 self.f.set(self.f.get() + 1);
1565 if self.f.get() == 10 { fail!() }
1566 S { f: self.f, boxes: self.boxes.clone() }
1570 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1571 let _ = Vec::from_elem(100, s);
1576 fn test_grow_fn_fail() {
1578 v.grow_fn(100, |i| {
1582 (box 0i, Rc::new(0i))
1588 fn test_permute_fail() {
1589 let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
1590 (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
1592 for _ in v.permutations() {
1602 fn test_copy_memory_oob() {
1604 let mut a = [1i, 2, 3, 4];
1605 let b = [1i, 2, 3, 4, 5];
1611 fn test_total_ord() {
1612 let c: &[int] = &[1, 2, 3];
1613 [1, 2, 3, 4].cmp(& c) == Greater;
1614 let c: &[int] = &[1, 2, 3, 4];
1615 [1, 2, 3].cmp(& c) == Less;
1616 let c: &[int] = &[1, 2, 3, 6];
1617 [1, 2, 3, 4].cmp(& c) == Equal;
1618 let c: &[int] = &[1, 2, 3, 4, 5, 6];
1619 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& c) == Less;
1620 let c: &[int] = &[1, 2, 3, 4];
1621 [2, 2].cmp(& c) == Greater;
1625 fn test_iterator() {
1626 let xs = [1i, 2, 5, 10, 11];
1627 let mut it = xs.iter();
1628 assert_eq!(it.size_hint(), (5, Some(5)));
1629 assert_eq!(it.next().unwrap(), &1);
1630 assert_eq!(it.size_hint(), (4, Some(4)));
1631 assert_eq!(it.next().unwrap(), &2);
1632 assert_eq!(it.size_hint(), (3, Some(3)));
1633 assert_eq!(it.next().unwrap(), &5);
1634 assert_eq!(it.size_hint(), (2, Some(2)));
1635 assert_eq!(it.next().unwrap(), &10);
1636 assert_eq!(it.size_hint(), (1, Some(1)));
1637 assert_eq!(it.next().unwrap(), &11);
1638 assert_eq!(it.size_hint(), (0, Some(0)));
1639 assert!(it.next().is_none());
1643 fn test_random_access_iterator() {
1644 let xs = [1i, 2, 5, 10, 11];
1645 let mut it = xs.iter();
1647 assert_eq!(it.indexable(), 5);
1648 assert_eq!(it.idx(0).unwrap(), &1);
1649 assert_eq!(it.idx(2).unwrap(), &5);
1650 assert_eq!(it.idx(4).unwrap(), &11);
1651 assert!(it.idx(5).is_none());
1653 assert_eq!(it.next().unwrap(), &1);
1654 assert_eq!(it.indexable(), 4);
1655 assert_eq!(it.idx(0).unwrap(), &2);
1656 assert_eq!(it.idx(3).unwrap(), &11);
1657 assert!(it.idx(4).is_none());
1659 assert_eq!(it.next().unwrap(), &2);
1660 assert_eq!(it.indexable(), 3);
1661 assert_eq!(it.idx(1).unwrap(), &10);
1662 assert!(it.idx(3).is_none());
1664 assert_eq!(it.next().unwrap(), &5);
1665 assert_eq!(it.indexable(), 2);
1666 assert_eq!(it.idx(1).unwrap(), &11);
1668 assert_eq!(it.next().unwrap(), &10);
1669 assert_eq!(it.indexable(), 1);
1670 assert_eq!(it.idx(0).unwrap(), &11);
1671 assert!(it.idx(1).is_none());
1673 assert_eq!(it.next().unwrap(), &11);
1674 assert_eq!(it.indexable(), 0);
1675 assert!(it.idx(0).is_none());
1677 assert!(it.next().is_none());
1681 fn test_iter_size_hints() {
1682 let mut xs = [1i, 2, 5, 10, 11];
1683 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1684 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1688 fn test_iter_clone() {
1689 let xs = [1i, 2, 5];
1690 let mut it = xs.iter();
1692 let mut jt = it.clone();
1693 assert_eq!(it.next(), jt.next());
1694 assert_eq!(it.next(), jt.next());
1695 assert_eq!(it.next(), jt.next());
1699 fn test_mut_iterator() {
1700 let mut xs = [1i, 2, 3, 4, 5];
1701 for x in xs.mut_iter() {
1704 assert!(xs == [2, 3, 4, 5, 6])
1708 fn test_rev_iterator() {
1710 let xs = [1i, 2, 5, 10, 11];
1711 let ys = [11, 10, 5, 2, 1];
1713 for &x in xs.iter().rev() {
1714 assert_eq!(x, ys[i]);
1721 fn test_mut_rev_iterator() {
1722 let mut xs = [1u, 2, 3, 4, 5];
1723 for (i,x) in xs.mut_iter().rev().enumerate() {
1726 assert!(xs == [5, 5, 5, 5, 5])
1730 fn test_move_iterator() {
1731 let xs = vec![1u,2,3,4,5];
1732 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1736 fn test_move_rev_iterator() {
1737 let xs = vec![1u,2,3,4,5];
1738 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1742 fn test_splitator() {
1743 let xs = &[1i,2,3,4,5];
1745 let splits: &[&[int]] = &[&[1], &[3], &[5]];
1746 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1748 let splits: &[&[int]] = &[&[], &[2,3,4,5]];
1749 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
1751 let splits: &[&[int]] = &[&[1,2,3,4], &[]];
1752 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
1754 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1755 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
1757 let splits: &[&[int]] = &[&[], &[], &[], &[], &[], &[]];
1758 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
1761 let xs: &[int] = &[];
1762 let splits: &[&[int]] = &[&[]];
1763 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1767 fn test_splitnator() {
1768 let xs = &[1i,2,3,4,5];
1770 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1771 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1773 let splits: &[&[int]] = &[&[1], &[3,4,5]];
1774 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1776 let splits: &[&[int]] = &[&[], &[], &[], &[4,5]];
1777 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1780 let xs: &[int] = &[];
1781 let splits: &[&[int]] = &[&[]];
1782 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1786 fn test_rsplitator() {
1787 let xs = &[1i,2,3,4,5];
1789 let splits: &[&[int]] = &[&[5], &[3], &[1]];
1790 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
1792 let splits: &[&[int]] = &[&[2,3,4,5], &[]];
1793 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
1795 let splits: &[&[int]] = &[&[], &[1,2,3,4]];
1796 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
1798 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1799 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
1802 let xs: &[int] = &[];
1803 let splits: &[&[int]] = &[&[]];
1804 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), splits);
1808 fn test_rsplitnator() {
1809 let xs = &[1,2,3,4,5];
1811 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1812 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1814 let splits: &[&[int]] = &[&[5], &[1,2,3]];
1815 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1817 let splits: &[&[int]] = &[&[], &[], &[], &[1,2]];
1818 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1821 let xs: &[int] = &[];
1822 let splits: &[&[int]] = &[&[]];
1823 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1827 fn test_windowsator() {
1828 let v = &[1i,2,3,4];
1830 let wins: &[&[int]] = &[&[1,2], &[2,3], &[3,4]];
1831 assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), wins);
1832 let wins: &[&[int]] = &[&[1i,2,3], &[2,3,4]];
1833 assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), wins);
1834 assert!(v.windows(6).next().is_none());
1839 fn test_windowsator_0() {
1840 let v = &[1i,2,3,4];
1841 let _it = v.windows(0);
1845 fn test_chunksator() {
1846 let v = &[1i,2,3,4,5];
1848 let chunks: &[&[int]] = &[&[1i,2], &[3,4], &[5]];
1849 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), chunks);
1850 let chunks: &[&[int]] = &[&[1i,2,3], &[4,5]];
1851 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), chunks);
1852 let chunks: &[&[int]] = &[&[1i,2,3,4,5]];
1853 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), chunks);
1855 let chunks: &[&[int]] = &[&[5i], &[3,4], &[1,2]];
1856 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), chunks);
1857 let mut it = v.chunks(2);
1858 assert_eq!(it.indexable(), 3);
1859 let chunk: &[int] = &[1,2];
1860 assert_eq!(it.idx(0).unwrap(), chunk);
1861 let chunk: &[int] = &[3,4];
1862 assert_eq!(it.idx(1).unwrap(), chunk);
1863 let chunk: &[int] = &[5];
1864 assert_eq!(it.idx(2).unwrap(), chunk);
1865 assert_eq!(it.idx(3), None);
1870 fn test_chunksator_0() {
1871 let v = &[1i,2,3,4];
1872 let _it = v.chunks(0);
1876 fn test_move_from() {
1877 let mut a = [1i,2,3,4,5];
1878 let b = vec![6i,7,8];
1879 assert_eq!(a.move_from(b, 0, 3), 3);
1880 assert!(a == [6i,7,8,4,5]);
1881 let mut a = [7i,2,8,1];
1882 let b = vec![3i,1,4,1,5,9];
1883 assert_eq!(a.move_from(b, 0, 6), 4);
1884 assert!(a == [3i,1,4,1]);
1885 let mut a = [1i,2,3,4];
1886 let b = vec![5i,6,7,8,9,0];
1887 assert_eq!(a.move_from(b, 2, 3), 1);
1888 assert!(a == [7i,2,3,4]);
1889 let mut a = [1i,2,3,4,5];
1890 let b = vec![5i,6,7,8,9,0];
1891 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1892 assert!(a == [1i,2,6,7,5]);
1896 fn test_copy_from() {
1897 let mut a = [1i,2,3,4,5];
1899 assert_eq!(a.copy_from(b), 3);
1900 assert!(a == [6i,7,8,4,5]);
1901 let mut c = [7i,2,8,1];
1902 let d = [3i,1,4,1,5,9];
1903 assert_eq!(c.copy_from(d), 4);
1904 assert!(c == [3i,1,4,1]);
1908 fn test_reverse_part() {
1909 let mut values = [1i,2,3,4,5];
1910 values.mut_slice(1, 4).reverse();
1911 assert!(values == [1,4,3,2,5]);
1916 macro_rules! test_show_vec(
1917 ($x:expr, $x_str:expr) => ({
1918 let (x, x_str) = ($x, $x_str);
1919 assert_eq!(format!("{}", x), x_str);
1920 assert_eq!(format!("{}", x.as_slice()), x_str);
1923 let empty: Vec<int> = vec![];
1924 test_show_vec!(empty, "[]".to_string());
1925 test_show_vec!(vec![1i], "[1]".to_string());
1926 test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
1927 test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
1928 "[[], [1], [1, 1]]".to_string());
1930 let empty_mut: &mut [int] = &mut[];
1931 test_show_vec!(empty_mut, "[]".to_string());
1932 let v: &mut[int] = &mut[1];
1933 test_show_vec!(v, "[1]".to_string());
1934 let v: &mut[int] = &mut[1, 2, 3];
1935 test_show_vec!(v, "[1, 2, 3]".to_string());
1936 let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]];
1937 test_show_vec!(v, "[[], [1], [1, 1]]".to_string());
1941 fn test_vec_default() {
1944 let v: $ty = Default::default();
1945 assert!(v.is_empty());
1954 fn test_bytes_set_memory() {
1955 use slice::bytes::MutableByteVector;
1956 let mut values = [1u8,2,3,4,5];
1957 values.mut_slice(0,5).set_memory(0xAB);
1958 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1959 values.mut_slice(2,4).set_memory(0xFF);
1960 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1965 fn test_overflow_does_not_cause_segfault() {
1967 v.reserve_exact(-1);
1974 fn test_overflow_does_not_cause_segfault_managed() {
1975 let mut v = vec![Rc::new(1i)];
1976 v.reserve_exact(-1);
1977 v.push(Rc::new(2i));
1981 fn test_mut_split_at() {
1982 let mut values = [1u8,2,3,4,5];
1984 let (left, right) = values.mut_split_at(2);
1985 assert!(left.slice(0, left.len()) == [1, 2]);
1986 for p in left.mut_iter() {
1990 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1991 for p in right.mut_iter() {
1996 assert!(values == [2, 3, 5, 6, 7]);
1999 #[deriving(Clone, PartialEq)]
2003 fn test_iter_zero_sized() {
2004 let mut v = vec![Foo, Foo, Foo];
2005 assert_eq!(v.len(), 3);
2014 for f in v.slice(1, 3).iter() {
2020 for f in v.mut_iter() {
2026 for f in v.move_iter() {
2030 assert_eq!(cnt, 11);
2032 let xs: [Foo, ..3] = [Foo, Foo, Foo];
2034 for f in xs.iter() {
2042 fn test_shrink_to_fit() {
2043 let mut xs = vec![0, 1, 2, 3];
2044 for i in range(4i, 100) {
2047 assert_eq!(xs.capacity(), 128);
2049 assert_eq!(xs.capacity(), 100);
2050 assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
2054 fn test_starts_with() {
2055 assert!(b"foobar".starts_with(b"foo"));
2056 assert!(!b"foobar".starts_with(b"oob"));
2057 assert!(!b"foobar".starts_with(b"bar"));
2058 assert!(!b"foo".starts_with(b"foobar"));
2059 assert!(!b"bar".starts_with(b"foobar"));
2060 assert!(b"foobar".starts_with(b"foobar"));
2061 let empty: &[u8] = [];
2062 assert!(empty.starts_with(empty));
2063 assert!(!empty.starts_with(b"foo"));
2064 assert!(b"foobar".starts_with(empty));
2068 fn test_ends_with() {
2069 assert!(b"foobar".ends_with(b"bar"));
2070 assert!(!b"foobar".ends_with(b"oba"));
2071 assert!(!b"foobar".ends_with(b"foo"));
2072 assert!(!b"foo".ends_with(b"foobar"));
2073 assert!(!b"bar".ends_with(b"foobar"));
2074 assert!(b"foobar".ends_with(b"foobar"));
2075 let empty: &[u8] = [];
2076 assert!(empty.ends_with(empty));
2077 assert!(!empty.ends_with(b"foo"));
2078 assert!(b"foobar".ends_with(empty));
2082 fn test_shift_ref() {
2083 let mut x: &[int] = [1, 2, 3, 4, 5];
2084 let h = x.shift_ref();
2085 assert_eq!(*h.unwrap(), 1);
2086 assert_eq!(x.len(), 4);
2087 assert_eq!(x[0], 2);
2088 assert_eq!(x[3], 5);
2090 let mut y: &[int] = [];
2091 assert_eq!(y.shift_ref(), None);
2096 let mut x: &[int] = [1, 2, 3, 4, 5];
2097 let h = x.pop_ref();
2098 assert_eq!(*h.unwrap(), 5);
2099 assert_eq!(x.len(), 4);
2100 assert_eq!(x[0], 1);
2101 assert_eq!(x[3], 4);
2103 let mut y: &[int] = [];
2104 assert!(y.pop_ref().is_none());
2108 fn test_mut_splitator() {
2109 let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2110 assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
2111 for slice in xs.mut_split(|x| *x == 0) {
2114 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2116 let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2117 for slice in xs.mut_split(|x| *x == 0).take(5) {
2120 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2124 fn test_mut_splitator_rev() {
2125 let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2126 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2129 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2134 let mut v = [0i,1,2];
2135 assert_eq!(v.get_mut(3), None);
2136 v.get_mut(1).map(|e| *e = 7);
2137 assert_eq!(v[1], 7);
2139 assert_eq!(v.get_mut(2), Some(&mut x));
2143 fn test_mut_chunks() {
2144 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2145 for (i, chunk) in v.mut_chunks(3).enumerate() {
2146 for x in chunk.mut_iter() {
2150 let result = [0u8, 0, 0, 1, 1, 1, 2];
2151 assert!(v == result);
2155 fn test_mut_chunks_rev() {
2156 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2157 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2158 for x in chunk.mut_iter() {
2162 let result = [2u8, 2, 2, 1, 1, 1, 0];
2163 assert!(v == result);
2168 fn test_mut_chunks_0() {
2169 let mut v = [1i, 2, 3, 4];
2170 let _it = v.mut_chunks(0);
2174 fn test_mut_shift_ref() {
2175 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2176 let h = x.mut_shift_ref();
2177 assert_eq!(*h.unwrap(), 1);
2178 assert_eq!(x.len(), 4);
2179 assert_eq!(x[0], 2);
2180 assert_eq!(x[3], 5);
2182 let mut y: &mut [int] = [];
2183 assert!(y.mut_shift_ref().is_none());
2187 fn test_mut_pop_ref() {
2188 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2189 let h = x.mut_pop_ref();
2190 assert_eq!(*h.unwrap(), 5);
2191 assert_eq!(x.len(), 4);
2192 assert_eq!(x[0], 1);
2193 assert_eq!(x[3], 4);
2195 let mut y: &mut [int] = [];
2196 assert!(y.mut_pop_ref().is_none());
2200 fn test_mut_last() {
2201 let mut x = [1i, 2, 3, 4, 5];
2202 let h = x.mut_last();
2203 assert_eq!(*h.unwrap(), 5);
2205 let y: &mut [int] = [];
2206 assert!(y.mut_last().is_none());
2212 use std::prelude::*;
2213 use std::rand::{weak_rng, Rng};
2222 fn iterator(b: &mut Bencher) {
2223 // peculiar numbers to stop LLVM from optimising the summation
2225 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2232 // sum == 11806, to stop dead code elimination.
2233 if sum == 0 {fail!()}
2238 fn mut_iterator(b: &mut Bencher) {
2239 let mut v = Vec::from_elem(100, 0i);
2243 for x in v.mut_iter() {
2251 fn concat(b: &mut Bencher) {
2252 let xss: Vec<Vec<uint>> =
2253 Vec::from_fn(100, |i| range(0u, i).collect());
2255 xss.as_slice().concat_vec()
2260 fn connect(b: &mut Bencher) {
2261 let xss: Vec<Vec<uint>> =
2262 Vec::from_fn(100, |i| range(0u, i).collect());
2264 xss.as_slice().connect_vec(&0)
2269 fn push(b: &mut Bencher) {
2270 let mut vec: Vec<uint> = vec![];
2278 fn starts_with_same_vector(b: &mut Bencher) {
2279 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2281 vec.as_slice().starts_with(vec.as_slice())
2286 fn starts_with_single_element(b: &mut Bencher) {
2287 let vec: Vec<uint> = vec![0];
2289 vec.as_slice().starts_with(vec.as_slice())
2294 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2295 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2296 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2299 vec.as_slice().starts_with(match_vec.as_slice())
2304 fn ends_with_same_vector(b: &mut Bencher) {
2305 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2307 vec.as_slice().ends_with(vec.as_slice())
2312 fn ends_with_single_element(b: &mut Bencher) {
2313 let vec: Vec<uint> = vec![0];
2315 vec.as_slice().ends_with(vec.as_slice())
2320 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2321 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2322 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2323 match_vec.as_mut_slice()[0] = 200;
2325 vec.as_slice().starts_with(match_vec.as_slice())
2330 fn contains_last_element(b: &mut Bencher) {
2331 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2338 fn zero_1kb_from_elem(b: &mut Bencher) {
2340 Vec::from_elem(1024, 0u8)
2345 fn zero_1kb_set_memory(b: &mut Bencher) {
2347 let mut v: Vec<uint> = Vec::with_capacity(1024);
2349 let vp = v.as_mut_ptr();
2350 ptr::set_memory(vp, 0, 1024);
2358 fn zero_1kb_loop_set(b: &mut Bencher) {
2360 let mut v: Vec<uint> = Vec::with_capacity(1024);
2364 for i in range(0u, 1024) {
2371 fn zero_1kb_mut_iter(b: &mut Bencher) {
2373 let mut v = Vec::with_capacity(1024);
2377 for x in v.mut_iter() {
2385 fn random_inserts(b: &mut Bencher) {
2386 let mut rng = weak_rng();
2388 let mut v = Vec::from_elem(30, (0u, 0u));
2389 for _ in range(0u, 100) {
2391 v.insert(rng.gen::<uint>() % (l + 1),
2397 fn random_removes(b: &mut Bencher) {
2398 let mut rng = weak_rng();
2400 let mut v = Vec::from_elem(130, (0u, 0u));
2401 for _ in range(0u, 100) {
2403 v.remove(rng.gen::<uint>() % l);
2409 fn sort_random_small(b: &mut Bencher) {
2410 let mut rng = weak_rng();
2412 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
2413 v.as_mut_slice().sort();
2415 b.bytes = 5 * mem::size_of::<u64>() as u64;
2419 fn sort_random_medium(b: &mut Bencher) {
2420 let mut rng = weak_rng();
2422 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
2423 v.as_mut_slice().sort();
2425 b.bytes = 100 * mem::size_of::<u64>() as u64;
2429 fn sort_random_large(b: &mut Bencher) {
2430 let mut rng = weak_rng();
2432 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
2433 v.as_mut_slice().sort();
2435 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2439 fn sort_sorted(b: &mut Bencher) {
2440 let mut v = Vec::from_fn(10000, |i| i);
2444 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2447 type BigSortable = (u64,u64,u64,u64);
2450 fn sort_big_random_small(b: &mut Bencher) {
2451 let mut rng = weak_rng();
2453 let mut v = rng.gen_iter::<BigSortable>().take(5)
2454 .collect::<Vec<BigSortable>>();
2457 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2461 fn sort_big_random_medium(b: &mut Bencher) {
2462 let mut rng = weak_rng();
2464 let mut v = rng.gen_iter::<BigSortable>().take(100)
2465 .collect::<Vec<BigSortable>>();
2468 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2472 fn sort_big_random_large(b: &mut Bencher) {
2473 let mut rng = weak_rng();
2475 let mut v = rng.gen_iter::<BigSortable>().take(10000)
2476 .collect::<Vec<BigSortable>>();
2479 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2483 fn sort_big_sorted(b: &mut Bencher) {
2484 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2488 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;