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![];
869 let mut a = vec![11i, 12, 13];
870 let b: &[int] = &[11, 12, 13];
871 assert_eq!(a.tailn(0), b);
872 a = vec![11i, 12, 13];
873 let b: &[int] = &[13];
874 assert_eq!(a.tailn(2), b);
880 fn test_tailn_empty() {
881 let a: Vec<int> = vec![];
887 let mut a = vec![11i];
889 assert_eq!(a.init(), b);
891 let b: &[int] = &[11];
892 assert_eq!(a.init(), b);
897 fn test_init_empty() {
898 let a: Vec<int> = vec![];
904 let mut a = vec![11i, 12, 13];
905 let b: &[int] = &[11, 12, 13];
906 assert_eq!(a.as_slice().initn(0), b);
907 a = vec![11i, 12, 13];
908 let b: &[int] = &[11];
909 assert_eq!(a.as_slice().initn(2), b);
915 fn test_initn_empty() {
916 let a: Vec<int> = vec![];
917 a.as_slice().initn(2);
923 assert_eq!(a.as_slice().last(), None);
925 assert_eq!(a.as_slice().last().unwrap(), &11);
927 assert_eq!(a.as_slice().last().unwrap(), &12);
932 // Test fixed length vector.
933 let vec_fixed = [1i, 2, 3, 4];
934 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_vec();
935 assert_eq!(v_a.len(), 3u);
936 let v_a = v_a.as_slice();
937 assert_eq!(v_a[0], 2);
938 assert_eq!(v_a[1], 3);
939 assert_eq!(v_a[2], 4);
942 let vec_stack = &[1i, 2, 3];
943 let v_b = vec_stack.slice(1u, 3u).to_vec();
944 assert_eq!(v_b.len(), 2u);
945 let v_b = v_b.as_slice();
946 assert_eq!(v_b[0], 2);
947 assert_eq!(v_b[1], 3);
950 let vec_unique = vec![1i, 2, 3, 4, 5, 6];
951 let v_d = vec_unique.slice(1u, 6u).to_vec();
952 assert_eq!(v_d.len(), 5u);
953 let v_d = v_d.as_slice();
954 assert_eq!(v_d[0], 2);
955 assert_eq!(v_d[1], 3);
956 assert_eq!(v_d[2], 4);
957 assert_eq!(v_d[3], 5);
958 assert_eq!(v_d[4], 6);
962 fn test_slice_from() {
963 let vec: &[int] = &[1, 2, 3, 4];
964 assert_eq!(vec.slice_from(0), vec);
965 let b: &[int] = &[3, 4];
966 assert_eq!(vec.slice_from(2), b);
968 assert_eq!(vec.slice_from(4), b);
973 let vec: &[int] = &[1, 2, 3, 4];
974 assert_eq!(vec.slice_to(4), vec);
975 let b: &[int] = &[1, 2];
976 assert_eq!(vec.slice_to(2), b);
978 assert_eq!(vec.slice_to(0), b);
984 let mut v = vec![5i];
986 assert_eq!(v.len(), 0);
987 assert_eq!(e, Some(5));
995 fn test_swap_remove() {
996 let mut v = vec![1i, 2, 3, 4, 5];
997 let mut e = v.swap_remove(0);
998 assert_eq!(e, Some(1));
999 assert_eq!(v, vec![5i, 2, 3, 4]);
1000 e = v.swap_remove(3);
1001 assert_eq!(e, Some(4));
1002 assert_eq!(v, vec![5i, 2, 3]);
1004 e = v.swap_remove(3);
1005 assert_eq!(e, None);
1006 assert_eq!(v, vec![5i, 2, 3]);
1010 fn test_swap_remove_noncopyable() {
1011 // Tests that we don't accidentally run destructors twice.
1012 let mut v = vec![rt::exclusive::Exclusive::new(()),
1013 rt::exclusive::Exclusive::new(()),
1014 rt::exclusive::Exclusive::new(())];
1015 let mut _e = v.swap_remove(0);
1016 assert_eq!(v.len(), 2);
1017 _e = v.swap_remove(1);
1018 assert_eq!(v.len(), 1);
1019 _e = v.swap_remove(0);
1020 assert_eq!(v.len(), 0);
1025 // Test on-stack push().
1028 assert_eq!(v.len(), 1u);
1029 assert_eq!(v.as_slice()[0], 1);
1031 // Test on-heap push().
1033 assert_eq!(v.len(), 2u);
1034 assert_eq!(v.as_slice()[0], 1);
1035 assert_eq!(v.as_slice()[1], 2);
1040 // Test on-stack grow().
1044 let v = v.as_slice();
1045 assert_eq!(v.len(), 2u);
1046 assert_eq!(v[0], 1);
1047 assert_eq!(v[1], 1);
1050 // Test on-heap grow().
1053 let v = v.as_slice();
1054 assert_eq!(v.len(), 5u);
1055 assert_eq!(v[0], 1);
1056 assert_eq!(v[1], 1);
1057 assert_eq!(v[2], 2);
1058 assert_eq!(v[3], 2);
1059 assert_eq!(v[4], 2);
1066 v.grow_fn(3u, square);
1067 let v = v.as_slice();
1068 assert_eq!(v.len(), 3u);
1069 assert_eq!(v[0], 0u);
1070 assert_eq!(v[1], 1u);
1071 assert_eq!(v[2], 4u);
1075 fn test_grow_set() {
1076 let mut v = vec![1i, 2, 3];
1077 v.grow_set(4u, &4, 5);
1078 let v = v.as_slice();
1079 assert_eq!(v.len(), 5u);
1080 assert_eq!(v[0], 1);
1081 assert_eq!(v[1], 2);
1082 assert_eq!(v[2], 3);
1083 assert_eq!(v[3], 4);
1084 assert_eq!(v[4], 5);
1088 fn test_truncate() {
1089 let mut v = vec![box 6i,box 5,box 4];
1091 let v = v.as_slice();
1092 assert_eq!(v.len(), 1);
1093 assert_eq!(*(v[0]), 6);
1094 // If the unsafe block didn't drop things properly, we blow up here.
1099 let mut v = vec![box 6i,box 5,box 4];
1101 assert_eq!(v.len(), 0);
1102 // If the unsafe block didn't drop things properly, we blow up here.
1107 fn case(a: Vec<uint>, b: Vec<uint>) {
1112 case(vec![], vec![]);
1113 case(vec![1u], vec![1]);
1114 case(vec![1u,1], vec![1]);
1115 case(vec![1u,2,3], vec![1,2,3]);
1116 case(vec![1u,1,2,3], vec![1,2,3]);
1117 case(vec![1u,2,2,3], vec![1,2,3]);
1118 case(vec![1u,2,3,3], vec![1,2,3]);
1119 case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1123 fn test_dedup_unique() {
1124 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1126 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1128 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1131 * If the boxed pointers were leaked or otherwise misused, valgrind
1132 * and/or rustrt should raise errors.
1137 fn test_dedup_shared() {
1138 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1140 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1142 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1145 * If the pointers were leaked or otherwise misused, valgrind and/or
1146 * rustrt should raise errors.
1152 let mut v = vec![1u, 2, 3, 4, 5];
1154 assert_eq!(v, vec![1u, 3, 5]);
1158 fn test_element_swaps() {
1159 let mut v = [1i, 2, 3];
1160 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1163 0 => assert!(v == [1, 3, 2]),
1164 1 => assert!(v == [3, 1, 2]),
1165 2 => assert!(v == [3, 2, 1]),
1166 3 => assert!(v == [2, 3, 1]),
1167 4 => assert!(v == [2, 1, 3]),
1168 5 => assert!(v == [1, 2, 3]),
1175 fn test_permutations() {
1177 let v: [int, ..0] = [];
1178 let mut it = v.permutations();
1179 let (min_size, max_opt) = it.size_hint();
1180 assert_eq!(min_size, 1);
1181 assert_eq!(max_opt.unwrap(), 1);
1182 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1183 assert_eq!(it.next(), None);
1186 let v = ["Hello".to_string()];
1187 let mut it = v.permutations();
1188 let (min_size, max_opt) = it.size_hint();
1189 assert_eq!(min_size, 1);
1190 assert_eq!(max_opt.unwrap(), 1);
1191 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1192 assert_eq!(it.next(), None);
1196 let mut it = v.permutations();
1197 let (min_size, max_opt) = it.size_hint();
1198 assert_eq!(min_size, 3*2);
1199 assert_eq!(max_opt.unwrap(), 3*2);
1200 assert_eq!(it.next(), Some(vec![1,2,3]));
1201 assert_eq!(it.next(), Some(vec![1,3,2]));
1202 assert_eq!(it.next(), Some(vec![3,1,2]));
1203 let (min_size, max_opt) = it.size_hint();
1204 assert_eq!(min_size, 3);
1205 assert_eq!(max_opt.unwrap(), 3);
1206 assert_eq!(it.next(), Some(vec![3,2,1]));
1207 assert_eq!(it.next(), Some(vec![2,3,1]));
1208 assert_eq!(it.next(), Some(vec![2,1,3]));
1209 assert_eq!(it.next(), None);
1212 // check that we have N! permutations
1213 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1215 let mut it = v.permutations();
1216 let (min_size, max_opt) = it.size_hint();
1220 assert_eq!(amt, it.swaps.swaps_made);
1221 assert_eq!(amt, min_size);
1222 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1223 assert_eq!(amt, max_opt.unwrap());
1228 fn test_lexicographic_permutations() {
1229 let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1230 assert!(v.prev_permutation() == false);
1231 assert!(v.next_permutation());
1232 let b: &mut[int] = &mut[1, 2, 3, 5, 4];
1234 assert!(v.prev_permutation());
1235 let b: &mut[int] = &mut[1, 2, 3, 4, 5];
1237 assert!(v.next_permutation());
1238 assert!(v.next_permutation());
1239 let b: &mut[int] = &mut[1, 2, 4, 3, 5];
1241 assert!(v.next_permutation());
1242 let b: &mut[int] = &mut[1, 2, 4, 5, 3];
1245 let v : &mut[int] = &mut[1i, 0, 0, 0];
1246 assert!(v.next_permutation() == false);
1247 assert!(v.prev_permutation());
1248 let b: &mut[int] = &mut[0, 1, 0, 0];
1250 assert!(v.prev_permutation());
1251 let b: &mut[int] = &mut[0, 0, 1, 0];
1253 assert!(v.prev_permutation());
1254 let b: &mut[int] = &mut[0, 0, 0, 1];
1256 assert!(v.prev_permutation() == false);
1260 fn test_lexicographic_permutations_empty_and_short() {
1261 let empty : &mut[int] = &mut[];
1262 assert!(empty.next_permutation() == false);
1263 let b: &mut[int] = &mut[];
1264 assert!(empty == b);
1265 assert!(empty.prev_permutation() == false);
1266 assert!(empty == b);
1268 let one_elem : &mut[int] = &mut[4i];
1269 assert!(one_elem.prev_permutation() == false);
1270 let b: &mut[int] = &mut[4];
1271 assert!(one_elem == b);
1272 assert!(one_elem.next_permutation() == false);
1273 assert!(one_elem == b);
1275 let two_elem : &mut[int] = &mut[1i, 2];
1276 assert!(two_elem.prev_permutation() == false);
1277 let b : &mut[int] = &mut[1, 2];
1278 let c : &mut[int] = &mut[2, 1];
1279 assert!(two_elem == b);
1280 assert!(two_elem.next_permutation());
1281 assert!(two_elem == c);
1282 assert!(two_elem.next_permutation() == false);
1283 assert!(two_elem == c);
1284 assert!(two_elem.prev_permutation());
1285 assert!(two_elem == b);
1286 assert!(two_elem.prev_permutation() == false);
1287 assert!(two_elem == b);
1291 fn test_position_elem() {
1292 assert!([].position_elem(&1i).is_none());
1294 let v1 = vec![1i, 2, 3, 3, 2, 5];
1295 assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
1296 assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
1297 assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
1298 assert!(v1.as_slice().position_elem(&4).is_none());
1302 fn test_bsearch_elem() {
1303 assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
1304 assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
1305 assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
1306 assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
1307 assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
1309 assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
1310 assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
1311 assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
1312 assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
1314 assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
1315 assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
1316 assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
1317 assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
1319 assert_eq!([2i,4,6].bsearch_elem(&1), None);
1320 assert_eq!([2i,4,6].bsearch_elem(&5), None);
1321 assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
1322 assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
1324 assert_eq!([2i,4].bsearch_elem(&1), None);
1325 assert_eq!([2i,4].bsearch_elem(&5), None);
1326 assert_eq!([2i,4].bsearch_elem(&2), Some(0));
1327 assert_eq!([2i,4].bsearch_elem(&4), Some(1));
1329 assert_eq!([2i].bsearch_elem(&1), None);
1330 assert_eq!([2i].bsearch_elem(&5), None);
1331 assert_eq!([2i].bsearch_elem(&2), Some(0));
1333 assert_eq!([].bsearch_elem(&1i), None);
1334 assert_eq!([].bsearch_elem(&5i), None);
1336 assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
1337 assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
1338 assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
1339 assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
1340 assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
1342 assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
1343 assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
1348 let mut v: Vec<int> = vec![10i, 20];
1349 assert_eq!(*v.get(0), 10);
1350 assert_eq!(*v.get(1), 20);
1352 assert_eq!(*v.get(0), 20);
1353 assert_eq!(*v.get(1), 10);
1355 let mut v3: Vec<int> = vec![];
1357 assert!(v3.is_empty());
1362 for len in range(4u, 25) {
1363 for _ in range(0i, 100) {
1364 let mut v = task_rng().gen_iter::<uint>().take(len)
1365 .collect::<Vec<uint>>();
1366 let mut v1 = v.clone();
1368 v.as_mut_slice().sort();
1369 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1371 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1372 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1374 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1375 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1379 // shouldn't fail/crash
1380 let mut v: [uint, .. 0] = [];
1383 let mut v = [0xDEADBEEFu];
1385 assert!(v == [0xDEADBEEF]);
1389 fn test_sort_stability() {
1390 for len in range(4i, 25) {
1391 for _ in range(0u, 10) {
1392 let mut counts = [0i, .. 10];
1394 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1395 // where the first item of each tuple is random, but
1396 // the second item represents which occurrence of that
1397 // number this element is, i.e. the second elements
1398 // will occur in sorted order.
1399 let mut v = range(0, len).map(|_| {
1400 let n = task_rng().gen::<uint>() % 10;
1403 }).collect::<Vec<(uint, int)>>();
1405 // only sort on the first element, so an unstable sort
1406 // may mix up the counts.
1407 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1409 // this comparison includes the count (the second item
1410 // of the tuple), so elements with equal first items
1411 // will need to be ordered with increasing
1412 // counts... i.e. exactly asserting that this sort is
1414 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1420 fn test_partition() {
1421 assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
1422 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1423 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1424 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1428 fn test_partitioned() {
1429 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
1430 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1431 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1432 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1437 let v: [Vec<int>, ..0] = [];
1438 assert_eq!(v.concat_vec(), vec![]);
1439 assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
1441 let v: [&[int], ..2] = [&[1], &[2, 3]];
1442 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
1443 let v: [&[int], ..3] = [&[1], &[2], &[3]];
1444 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
1449 let v: [Vec<int>, ..0] = [];
1450 assert_eq!(v.connect_vec(&0), vec![]);
1451 assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1452 assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1454 let v: [&[int], ..2] = [&[1], &[2, 3]];
1455 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
1456 let v: [&[int], ..3] = [&[1], &[2], &[3]];
1457 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
1462 let mut x = vec![1i, 2, 3];
1463 assert_eq!(x.shift(), Some(1));
1464 assert_eq!(&x, &vec![2i, 3]);
1465 assert_eq!(x.shift(), Some(2));
1466 assert_eq!(x.shift(), Some(3));
1467 assert_eq!(x.shift(), None);
1468 assert_eq!(x.len(), 0);
1472 #[allow(deprecated)]
1474 let mut x = vec![1i, 2, 3];
1476 assert_eq!(x, vec![0, 1, 2, 3]);
1481 let mut a = vec![1i, 2, 4];
1483 assert_eq!(a, vec![1, 2, 3, 4]);
1485 let mut a = vec![1i, 2, 3];
1487 assert_eq!(a, vec![0, 1, 2, 3]);
1489 let mut a = vec![1i, 2, 3];
1491 assert_eq!(a, vec![1, 2, 3, 4]);
1495 assert_eq!(a, vec![1]);
1500 fn test_insert_oob() {
1501 let mut a = vec![1i, 2, 3];
1507 let mut a = vec![1i,2,3,4];
1509 assert_eq!(a.remove(2), Some(3));
1510 assert_eq!(a, vec![1i,2,4]);
1512 assert_eq!(a.remove(2), Some(4));
1513 assert_eq!(a, vec![1i,2]);
1515 assert_eq!(a.remove(2), None);
1516 assert_eq!(a, vec![1i,2]);
1518 assert_eq!(a.remove(0), Some(1));
1519 assert_eq!(a, vec![2i]);
1521 assert_eq!(a.remove(0), Some(2));
1522 assert_eq!(a, vec![]);
1524 assert_eq!(a.remove(0), None);
1525 assert_eq!(a.remove(10), None);
1529 fn test_capacity() {
1530 let mut v = vec![0u64];
1531 v.reserve_exact(10u);
1532 assert_eq!(v.capacity(), 10u);
1533 let mut v = vec![0u32];
1534 v.reserve_exact(10u);
1535 assert_eq!(v.capacity(), 10u);
1540 let v = vec![1i, 2, 3, 4, 5];
1541 let v = v.slice(1u, 3u);
1542 assert_eq!(v.len(), 2u);
1543 assert_eq!(v[0], 2);
1544 assert_eq!(v[1], 3);
1550 fn test_from_fn_fail() {
1551 Vec::from_fn(100, |v| {
1552 if v == 50 { fail!() }
1559 fn test_from_elem_fail() {
1563 boxes: (Box<int>, Rc<int>)
1567 fn clone(&self) -> S {
1568 self.f.set(self.f.get() + 1);
1569 if self.f.get() == 10 { fail!() }
1570 S { f: self.f, boxes: self.boxes.clone() }
1574 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1575 let _ = Vec::from_elem(100, s);
1580 fn test_grow_fn_fail() {
1582 v.grow_fn(100, |i| {
1586 (box 0i, Rc::new(0i))
1592 fn test_permute_fail() {
1593 let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
1594 (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
1596 for _ in v.permutations() {
1606 fn test_copy_memory_oob() {
1608 let mut a = [1i, 2, 3, 4];
1609 let b = [1i, 2, 3, 4, 5];
1615 fn test_total_ord() {
1616 let c: &[int] = &[1, 2, 3];
1617 [1, 2, 3, 4].cmp(& c) == Greater;
1618 let c: &[int] = &[1, 2, 3, 4];
1619 [1, 2, 3].cmp(& c) == Less;
1620 let c: &[int] = &[1, 2, 3, 6];
1621 [1, 2, 3, 4].cmp(& c) == Equal;
1622 let c: &[int] = &[1, 2, 3, 4, 5, 6];
1623 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& c) == Less;
1624 let c: &[int] = &[1, 2, 3, 4];
1625 [2, 2].cmp(& c) == Greater;
1629 fn test_iterator() {
1630 let xs = [1i, 2, 5, 10, 11];
1631 let mut it = xs.iter();
1632 assert_eq!(it.size_hint(), (5, Some(5)));
1633 assert_eq!(it.next().unwrap(), &1);
1634 assert_eq!(it.size_hint(), (4, Some(4)));
1635 assert_eq!(it.next().unwrap(), &2);
1636 assert_eq!(it.size_hint(), (3, Some(3)));
1637 assert_eq!(it.next().unwrap(), &5);
1638 assert_eq!(it.size_hint(), (2, Some(2)));
1639 assert_eq!(it.next().unwrap(), &10);
1640 assert_eq!(it.size_hint(), (1, Some(1)));
1641 assert_eq!(it.next().unwrap(), &11);
1642 assert_eq!(it.size_hint(), (0, Some(0)));
1643 assert!(it.next().is_none());
1647 fn test_random_access_iterator() {
1648 let xs = [1i, 2, 5, 10, 11];
1649 let mut it = xs.iter();
1651 assert_eq!(it.indexable(), 5);
1652 assert_eq!(it.idx(0).unwrap(), &1);
1653 assert_eq!(it.idx(2).unwrap(), &5);
1654 assert_eq!(it.idx(4).unwrap(), &11);
1655 assert!(it.idx(5).is_none());
1657 assert_eq!(it.next().unwrap(), &1);
1658 assert_eq!(it.indexable(), 4);
1659 assert_eq!(it.idx(0).unwrap(), &2);
1660 assert_eq!(it.idx(3).unwrap(), &11);
1661 assert!(it.idx(4).is_none());
1663 assert_eq!(it.next().unwrap(), &2);
1664 assert_eq!(it.indexable(), 3);
1665 assert_eq!(it.idx(1).unwrap(), &10);
1666 assert!(it.idx(3).is_none());
1668 assert_eq!(it.next().unwrap(), &5);
1669 assert_eq!(it.indexable(), 2);
1670 assert_eq!(it.idx(1).unwrap(), &11);
1672 assert_eq!(it.next().unwrap(), &10);
1673 assert_eq!(it.indexable(), 1);
1674 assert_eq!(it.idx(0).unwrap(), &11);
1675 assert!(it.idx(1).is_none());
1677 assert_eq!(it.next().unwrap(), &11);
1678 assert_eq!(it.indexable(), 0);
1679 assert!(it.idx(0).is_none());
1681 assert!(it.next().is_none());
1685 fn test_iter_size_hints() {
1686 let mut xs = [1i, 2, 5, 10, 11];
1687 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1688 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1692 fn test_iter_clone() {
1693 let xs = [1i, 2, 5];
1694 let mut it = xs.iter();
1696 let mut jt = it.clone();
1697 assert_eq!(it.next(), jt.next());
1698 assert_eq!(it.next(), jt.next());
1699 assert_eq!(it.next(), jt.next());
1703 fn test_mut_iterator() {
1704 let mut xs = [1i, 2, 3, 4, 5];
1705 for x in xs.mut_iter() {
1708 assert!(xs == [2, 3, 4, 5, 6])
1712 fn test_rev_iterator() {
1714 let xs = [1i, 2, 5, 10, 11];
1715 let ys = [11, 10, 5, 2, 1];
1717 for &x in xs.iter().rev() {
1718 assert_eq!(x, ys[i]);
1725 fn test_mut_rev_iterator() {
1726 let mut xs = [1u, 2, 3, 4, 5];
1727 for (i,x) in xs.mut_iter().rev().enumerate() {
1730 assert!(xs == [5, 5, 5, 5, 5])
1734 fn test_move_iterator() {
1735 let xs = vec![1u,2,3,4,5];
1736 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1740 fn test_move_rev_iterator() {
1741 let xs = vec![1u,2,3,4,5];
1742 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1746 fn test_splitator() {
1747 let xs = &[1i,2,3,4,5];
1749 let splits: &[&[int]] = &[&[1], &[3], &[5]];
1750 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1752 let splits: &[&[int]] = &[&[], &[2,3,4,5]];
1753 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
1755 let splits: &[&[int]] = &[&[1,2,3,4], &[]];
1756 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
1758 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1759 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
1761 let splits: &[&[int]] = &[&[], &[], &[], &[], &[], &[]];
1762 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
1765 let xs: &[int] = &[];
1766 let splits: &[&[int]] = &[&[]];
1767 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1771 fn test_splitnator() {
1772 let xs = &[1i,2,3,4,5];
1774 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1775 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1777 let splits: &[&[int]] = &[&[1], &[3,4,5]];
1778 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1780 let splits: &[&[int]] = &[&[], &[], &[], &[4,5]];
1781 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1784 let xs: &[int] = &[];
1785 let splits: &[&[int]] = &[&[]];
1786 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1790 fn test_rsplitator() {
1791 let xs = &[1i,2,3,4,5];
1793 let splits: &[&[int]] = &[&[5], &[3], &[1]];
1794 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
1796 let splits: &[&[int]] = &[&[2,3,4,5], &[]];
1797 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
1799 let splits: &[&[int]] = &[&[], &[1,2,3,4]];
1800 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
1802 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1803 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
1806 let xs: &[int] = &[];
1807 let splits: &[&[int]] = &[&[]];
1808 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), splits);
1812 fn test_rsplitnator() {
1813 let xs = &[1,2,3,4,5];
1815 let splits: &[&[int]] = &[&[1,2,3,4,5]];
1816 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1818 let splits: &[&[int]] = &[&[5], &[1,2,3]];
1819 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1821 let splits: &[&[int]] = &[&[], &[], &[], &[1,2]];
1822 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1825 let xs: &[int] = &[];
1826 let splits: &[&[int]] = &[&[]];
1827 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
1831 fn test_windowsator() {
1832 let v = &[1i,2,3,4];
1834 let wins: &[&[int]] = &[&[1,2], &[2,3], &[3,4]];
1835 assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), wins);
1836 let wins: &[&[int]] = &[&[1i,2,3], &[2,3,4]];
1837 assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), wins);
1838 assert!(v.windows(6).next().is_none());
1843 fn test_windowsator_0() {
1844 let v = &[1i,2,3,4];
1845 let _it = v.windows(0);
1849 fn test_chunksator() {
1850 let v = &[1i,2,3,4,5];
1852 let chunks: &[&[int]] = &[&[1i,2], &[3,4], &[5]];
1853 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), chunks);
1854 let chunks: &[&[int]] = &[&[1i,2,3], &[4,5]];
1855 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), chunks);
1856 let chunks: &[&[int]] = &[&[1i,2,3,4,5]];
1857 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), chunks);
1859 let chunks: &[&[int]] = &[&[5i], &[3,4], &[1,2]];
1860 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), chunks);
1861 let mut it = v.chunks(2);
1862 assert_eq!(it.indexable(), 3);
1863 let chunk: &[int] = &[1,2];
1864 assert_eq!(it.idx(0).unwrap(), chunk);
1865 let chunk: &[int] = &[3,4];
1866 assert_eq!(it.idx(1).unwrap(), chunk);
1867 let chunk: &[int] = &[5];
1868 assert_eq!(it.idx(2).unwrap(), chunk);
1869 assert_eq!(it.idx(3), None);
1874 fn test_chunksator_0() {
1875 let v = &[1i,2,3,4];
1876 let _it = v.chunks(0);
1880 fn test_move_from() {
1881 let mut a = [1i,2,3,4,5];
1882 let b = vec![6i,7,8];
1883 assert_eq!(a.move_from(b, 0, 3), 3);
1884 assert!(a == [6i,7,8,4,5]);
1885 let mut a = [7i,2,8,1];
1886 let b = vec![3i,1,4,1,5,9];
1887 assert_eq!(a.move_from(b, 0, 6), 4);
1888 assert!(a == [3i,1,4,1]);
1889 let mut a = [1i,2,3,4];
1890 let b = vec![5i,6,7,8,9,0];
1891 assert_eq!(a.move_from(b, 2, 3), 1);
1892 assert!(a == [7i,2,3,4]);
1893 let mut a = [1i,2,3,4,5];
1894 let b = vec![5i,6,7,8,9,0];
1895 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1896 assert!(a == [1i,2,6,7,5]);
1900 fn test_copy_from() {
1901 let mut a = [1i,2,3,4,5];
1903 assert_eq!(a.copy_from(b), 3);
1904 assert!(a == [6i,7,8,4,5]);
1905 let mut c = [7i,2,8,1];
1906 let d = [3i,1,4,1,5,9];
1907 assert_eq!(c.copy_from(d), 4);
1908 assert!(c == [3i,1,4,1]);
1912 fn test_reverse_part() {
1913 let mut values = [1i,2,3,4,5];
1914 values.mut_slice(1, 4).reverse();
1915 assert!(values == [1,4,3,2,5]);
1920 macro_rules! test_show_vec(
1921 ($x:expr, $x_str:expr) => ({
1922 let (x, x_str) = ($x, $x_str);
1923 assert_eq!(format!("{}", x), x_str);
1924 assert_eq!(format!("{}", x.as_slice()), x_str);
1927 let empty: Vec<int> = vec![];
1928 test_show_vec!(empty, "[]".to_string());
1929 test_show_vec!(vec![1i], "[1]".to_string());
1930 test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
1931 test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
1932 "[[], [1], [1, 1]]".to_string());
1934 let empty_mut: &mut [int] = &mut[];
1935 test_show_vec!(empty_mut, "[]".to_string());
1936 let v: &mut[int] = &mut[1];
1937 test_show_vec!(v, "[1]".to_string());
1938 let v: &mut[int] = &mut[1, 2, 3];
1939 test_show_vec!(v, "[1, 2, 3]".to_string());
1940 let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]];
1941 test_show_vec!(v, "[[], [1], [1, 1]]".to_string());
1945 fn test_vec_default() {
1948 let v: $ty = Default::default();
1949 assert!(v.is_empty());
1958 fn test_bytes_set_memory() {
1959 use slice::bytes::MutableByteVector;
1960 let mut values = [1u8,2,3,4,5];
1961 values.mut_slice(0,5).set_memory(0xAB);
1962 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1963 values.mut_slice(2,4).set_memory(0xFF);
1964 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1969 fn test_overflow_does_not_cause_segfault() {
1971 v.reserve_exact(-1);
1978 fn test_overflow_does_not_cause_segfault_managed() {
1979 let mut v = vec![Rc::new(1i)];
1980 v.reserve_exact(-1);
1981 v.push(Rc::new(2i));
1985 fn test_mut_split_at() {
1986 let mut values = [1u8,2,3,4,5];
1988 let (left, right) = values.mut_split_at(2);
1989 assert!(left.slice(0, left.len()) == [1, 2]);
1990 for p in left.mut_iter() {
1994 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1995 for p in right.mut_iter() {
2000 assert!(values == [2, 3, 5, 6, 7]);
2003 #[deriving(Clone, PartialEq)]
2007 fn test_iter_zero_sized() {
2008 let mut v = vec![Foo, Foo, Foo];
2009 assert_eq!(v.len(), 3);
2018 for f in v.slice(1, 3).iter() {
2024 for f in v.mut_iter() {
2030 for f in v.move_iter() {
2034 assert_eq!(cnt, 11);
2036 let xs: [Foo, ..3] = [Foo, Foo, Foo];
2038 for f in xs.iter() {
2046 fn test_shrink_to_fit() {
2047 let mut xs = vec![0, 1, 2, 3];
2048 for i in range(4i, 100) {
2051 assert_eq!(xs.capacity(), 128);
2053 assert_eq!(xs.capacity(), 100);
2054 assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
2058 fn test_starts_with() {
2059 assert!(b"foobar".starts_with(b"foo"));
2060 assert!(!b"foobar".starts_with(b"oob"));
2061 assert!(!b"foobar".starts_with(b"bar"));
2062 assert!(!b"foo".starts_with(b"foobar"));
2063 assert!(!b"bar".starts_with(b"foobar"));
2064 assert!(b"foobar".starts_with(b"foobar"));
2065 let empty: &[u8] = [];
2066 assert!(empty.starts_with(empty));
2067 assert!(!empty.starts_with(b"foo"));
2068 assert!(b"foobar".starts_with(empty));
2072 fn test_ends_with() {
2073 assert!(b"foobar".ends_with(b"bar"));
2074 assert!(!b"foobar".ends_with(b"oba"));
2075 assert!(!b"foobar".ends_with(b"foo"));
2076 assert!(!b"foo".ends_with(b"foobar"));
2077 assert!(!b"bar".ends_with(b"foobar"));
2078 assert!(b"foobar".ends_with(b"foobar"));
2079 let empty: &[u8] = [];
2080 assert!(empty.ends_with(empty));
2081 assert!(!empty.ends_with(b"foo"));
2082 assert!(b"foobar".ends_with(empty));
2086 #[allow(deprecated)]
2087 fn test_shift_ref() {
2088 let mut x: &[int] = [1, 2, 3, 4, 5];
2089 let h = x.shift_ref();
2090 assert_eq!(*h.unwrap(), 1);
2091 assert_eq!(x.len(), 4);
2092 assert_eq!(x[0], 2);
2093 assert_eq!(x[3], 5);
2095 let mut y: &[int] = [];
2096 assert_eq!(y.shift_ref(), None);
2100 #[allow(deprecated)]
2102 let mut x: &[int] = [1, 2, 3, 4, 5];
2103 let h = x.pop_ref();
2104 assert_eq!(*h.unwrap(), 5);
2105 assert_eq!(x.len(), 4);
2106 assert_eq!(x[0], 1);
2107 assert_eq!(x[3], 4);
2109 let mut y: &[int] = [];
2110 assert!(y.pop_ref().is_none());
2114 fn test_mut_splitator() {
2115 let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2116 assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
2117 for slice in xs.mut_split(|x| *x == 0) {
2120 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2122 let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2123 for slice in xs.mut_split(|x| *x == 0).take(5) {
2126 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2130 fn test_mut_splitator_rev() {
2131 let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2132 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2135 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2140 let mut v = [0i,1,2];
2141 assert_eq!(v.get_mut(3), None);
2142 v.get_mut(1).map(|e| *e = 7);
2143 assert_eq!(v[1], 7);
2145 assert_eq!(v.get_mut(2), Some(&mut x));
2149 fn test_mut_chunks() {
2150 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2151 for (i, chunk) in v.mut_chunks(3).enumerate() {
2152 for x in chunk.mut_iter() {
2156 let result = [0u8, 0, 0, 1, 1, 1, 2];
2157 assert!(v == result);
2161 fn test_mut_chunks_rev() {
2162 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2163 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2164 for x in chunk.mut_iter() {
2168 let result = [2u8, 2, 2, 1, 1, 1, 0];
2169 assert!(v == result);
2174 fn test_mut_chunks_0() {
2175 let mut v = [1i, 2, 3, 4];
2176 let _it = v.mut_chunks(0);
2180 #[allow(deprecated)]
2181 fn test_mut_shift_ref() {
2182 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2183 let h = x.mut_shift_ref();
2184 assert_eq!(*h.unwrap(), 1);
2185 assert_eq!(x.len(), 4);
2186 assert_eq!(x[0], 2);
2187 assert_eq!(x[3], 5);
2189 let mut y: &mut [int] = [];
2190 assert!(y.mut_shift_ref().is_none());
2194 #[allow(deprecated)]
2195 fn test_mut_pop_ref() {
2196 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2197 let h = x.mut_pop_ref();
2198 assert_eq!(*h.unwrap(), 5);
2199 assert_eq!(x.len(), 4);
2200 assert_eq!(x[0], 1);
2201 assert_eq!(x[3], 4);
2203 let mut y: &mut [int] = [];
2204 assert!(y.mut_pop_ref().is_none());
2208 fn test_mut_last() {
2209 let mut x = [1i, 2, 3, 4, 5];
2210 let h = x.mut_last();
2211 assert_eq!(*h.unwrap(), 5);
2213 let y: &mut [int] = [];
2214 assert!(y.mut_last().is_none());
2220 use std::prelude::*;
2221 use std::rand::{weak_rng, Rng};
2230 fn iterator(b: &mut Bencher) {
2231 // peculiar numbers to stop LLVM from optimising the summation
2233 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2240 // sum == 11806, to stop dead code elimination.
2241 if sum == 0 {fail!()}
2246 fn mut_iterator(b: &mut Bencher) {
2247 let mut v = Vec::from_elem(100, 0i);
2251 for x in v.mut_iter() {
2259 fn concat(b: &mut Bencher) {
2260 let xss: Vec<Vec<uint>> =
2261 Vec::from_fn(100, |i| range(0u, i).collect());
2263 xss.as_slice().concat_vec()
2268 fn connect(b: &mut Bencher) {
2269 let xss: Vec<Vec<uint>> =
2270 Vec::from_fn(100, |i| range(0u, i).collect());
2272 xss.as_slice().connect_vec(&0)
2277 fn push(b: &mut Bencher) {
2278 let mut vec: Vec<uint> = vec![];
2286 fn starts_with_same_vector(b: &mut Bencher) {
2287 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2289 vec.as_slice().starts_with(vec.as_slice())
2294 fn starts_with_single_element(b: &mut Bencher) {
2295 let vec: Vec<uint> = vec![0];
2297 vec.as_slice().starts_with(vec.as_slice())
2302 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2303 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2304 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2307 vec.as_slice().starts_with(match_vec.as_slice())
2312 fn ends_with_same_vector(b: &mut Bencher) {
2313 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2315 vec.as_slice().ends_with(vec.as_slice())
2320 fn ends_with_single_element(b: &mut Bencher) {
2321 let vec: Vec<uint> = vec![0];
2323 vec.as_slice().ends_with(vec.as_slice())
2328 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2329 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2330 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2331 match_vec.as_mut_slice()[0] = 200;
2333 vec.as_slice().starts_with(match_vec.as_slice())
2338 fn contains_last_element(b: &mut Bencher) {
2339 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2346 fn zero_1kb_from_elem(b: &mut Bencher) {
2348 Vec::from_elem(1024, 0u8)
2353 fn zero_1kb_set_memory(b: &mut Bencher) {
2355 let mut v: Vec<uint> = Vec::with_capacity(1024);
2357 let vp = v.as_mut_ptr();
2358 ptr::set_memory(vp, 0, 1024);
2366 fn zero_1kb_loop_set(b: &mut Bencher) {
2368 let mut v: Vec<uint> = Vec::with_capacity(1024);
2372 for i in range(0u, 1024) {
2379 fn zero_1kb_mut_iter(b: &mut Bencher) {
2381 let mut v = Vec::with_capacity(1024);
2385 for x in v.mut_iter() {
2393 fn random_inserts(b: &mut Bencher) {
2394 let mut rng = weak_rng();
2396 let mut v = Vec::from_elem(30, (0u, 0u));
2397 for _ in range(0u, 100) {
2399 v.insert(rng.gen::<uint>() % (l + 1),
2405 fn random_removes(b: &mut Bencher) {
2406 let mut rng = weak_rng();
2408 let mut v = Vec::from_elem(130, (0u, 0u));
2409 for _ in range(0u, 100) {
2411 v.remove(rng.gen::<uint>() % l);
2417 fn sort_random_small(b: &mut Bencher) {
2418 let mut rng = weak_rng();
2420 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
2421 v.as_mut_slice().sort();
2423 b.bytes = 5 * mem::size_of::<u64>() as u64;
2427 fn sort_random_medium(b: &mut Bencher) {
2428 let mut rng = weak_rng();
2430 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
2431 v.as_mut_slice().sort();
2433 b.bytes = 100 * mem::size_of::<u64>() as u64;
2437 fn sort_random_large(b: &mut Bencher) {
2438 let mut rng = weak_rng();
2440 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
2441 v.as_mut_slice().sort();
2443 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2447 fn sort_sorted(b: &mut Bencher) {
2448 let mut v = Vec::from_fn(10000, |i| i);
2452 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
2455 type BigSortable = (u64,u64,u64,u64);
2458 fn sort_big_random_small(b: &mut Bencher) {
2459 let mut rng = weak_rng();
2461 let mut v = rng.gen_iter::<BigSortable>().take(5)
2462 .collect::<Vec<BigSortable>>();
2465 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2469 fn sort_big_random_medium(b: &mut Bencher) {
2470 let mut rng = weak_rng();
2472 let mut v = rng.gen_iter::<BigSortable>().take(100)
2473 .collect::<Vec<BigSortable>>();
2476 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2480 fn sort_big_random_large(b: &mut Bencher) {
2481 let mut rng = weak_rng();
2483 let mut v = rng.gen_iter::<BigSortable>().take(10000)
2484 .collect::<Vec<BigSortable>>();
2487 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2491 fn sort_big_sorted(b: &mut Bencher) {
2492 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2496 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;