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!(1, 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] = &mut [1, 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 `Iter`, which
41 //! represents iteration over a slice.
45 //! A number of traits add methods that allow you to accomplish tasks
46 //! with slices, the most important being `SliceExt`. Other traits
47 //! apply only to slices of elements satisfying certain bounds (like
50 //! An example is the `slice` method which enables slicing syntax `[a..b]` that
51 //! returns an immutable "view" into a `Vec` or another slice from the index
52 //! interval `[a, b)`:
55 //! #![feature(slicing_syntax)]
57 //! let numbers = [0, 1, 2];
58 //! let last_numbers = numbers[1..3];
59 //! // last_numbers is now &[1, 2]
63 //! ## Implementations of other traits
65 //! There are several implementations of common traits for slices. Some examples
69 //! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
70 //! * `Hash` - for slices whose element type is `Hash`
74 //! The method `iter()` returns an iteration value for a slice. The iterator
75 //! yields references to the slice's elements, so if the element
76 //! type of the slice is `int`, the element type of the iterator is `&int`.
79 //! let numbers = [0, 1, 2];
80 //! for &x in numbers.iter() {
81 //! println!("{} is a number!", x);
85 //! * `.iter_mut()` returns an iterator that allows modifying each value.
86 //! * Further iterators exist that split, chunk or permute the slice.
88 #![doc(primitive = "slice")]
91 use alloc::boxed::Box;
92 use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned};
94 use core::iter::{range_step, MultiplicativeIterator};
95 use core::kinds::Sized;
96 use core::mem::size_of;
98 use core::ops::{FnMut,SliceMut};
99 use core::prelude::{Clone, Greater, Iterator, IteratorExt, Less, None, Option};
100 use core::prelude::{Ord, Ordering, PtrExt, Some, range, IteratorCloneExt, Result};
102 use core::slice as core_slice;
103 use self::Direction::*;
107 pub use core::slice::{Chunks, AsSlice, Windows};
108 pub use core::slice::{Iter, IterMut, PartialEqSliceExt};
109 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
110 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
111 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
112 pub use core::slice::{from_raw_buf, from_raw_mut_buf};
114 #[deprecated = "use Iter instead"]
115 pub type Items<'a, T:'a> = Iter<'a, T>;
117 #[deprecated = "use IterMut instead"]
118 pub type MutItems<'a, T:'a> = IterMut<'a, T>;
120 ////////////////////////////////////////////////////////////////////////////////
121 // Basic slice extension methods
122 ////////////////////////////////////////////////////////////////////////////////
124 /// Allocating extension methods for slices.
126 pub trait SliceExt for Sized? {
130 /// Sorts the slice, in place, using `compare` to compare
133 /// This sort is `O(n log n)` worst-case and stable, but allocates
134 /// approximately `2 * n`, where `n` is the length of `self`.
139 /// let mut v = [5, 4, 1, 3, 2];
140 /// v.sort_by(|a, b| a.cmp(b));
141 /// assert!(v == [1, 2, 3, 4, 5]);
143 /// // reverse sorting
144 /// v.sort_by(|a, b| b.cmp(a));
145 /// assert!(v == [5, 4, 3, 2, 1]);
148 fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering;
150 /// Consumes `src` and moves as many elements as it can into `self`
151 /// from the range [start,end).
153 /// Returns the number of elements copied (the shorter of `self.len()`
154 /// and `end - start`).
158 /// * src - A mutable vector of `T`
159 /// * start - The index into `src` to start copying from
160 /// * end - The index into `src` to stop copying from
165 /// let mut a = [1, 2, 3, 4, 5];
166 /// let b = vec![6, 7, 8];
167 /// let num_moved = a.move_from(b, 0, 3);
168 /// assert_eq!(num_moved, 3);
169 /// assert!(a == [6, 7, 8, 4, 5]);
171 #[experimental = "uncertain about this API approach"]
172 fn move_from(&mut self, src: Vec<T>, start: uint, end: uint) -> uint;
174 /// Returns a subslice spanning the interval [`start`, `end`).
176 /// Panics when the end of the new slice lies beyond the end of the
177 /// original slice (i.e. when `end > self.len()`) or when `start > end`.
179 /// Slicing with `start` equal to `end` yields an empty slice.
180 #[experimental = "will be replaced by slice syntax"]
181 fn slice(&self, start: uint, end: uint) -> &[T];
183 /// Returns a subslice from `start` to the end of the slice.
185 /// Panics when `start` is strictly greater than the length of the original slice.
187 /// Slicing from `self.len()` yields an empty slice.
188 #[experimental = "will be replaced by slice syntax"]
189 fn slice_from(&self, start: uint) -> &[T];
191 /// Returns a subslice from the start of the slice to `end`.
193 /// Panics when `end` is strictly greater than the length of the original slice.
195 /// Slicing to `0` yields an empty slice.
196 #[experimental = "will be replaced by slice syntax"]
197 fn slice_to(&self, end: uint) -> &[T];
199 /// Divides one slice into two at an index.
201 /// The first will contain all indices from `[0, mid)` (excluding
202 /// the index `mid` itself) and the second will contain all
203 /// indices from `[mid, len)` (excluding the index `len` itself).
205 /// Panics if `mid > len`.
207 fn split_at(&self, mid: uint) -> (&[T], &[T]);
209 /// Returns an iterator over the slice
211 fn iter(&self) -> Iter<T>;
213 /// Returns an iterator over subslices separated by elements that match
214 /// `pred`. The matched element is not contained in the subslices.
216 fn split<F>(&self, pred: F) -> Split<T, F>
217 where F: FnMut(&T) -> bool;
219 /// Returns an iterator over subslices separated by elements that match
220 /// `pred`, limited to splitting at most `n` times. The matched element is
221 /// not contained in the subslices.
223 fn splitn<F>(&self, n: uint, pred: F) -> SplitN<T, F>
224 where F: FnMut(&T) -> bool;
226 /// Returns an iterator over subslices separated by elements that match
227 /// `pred` limited to splitting at most `n` times. This starts at the end of
228 /// the slice and works backwards. The matched element is not contained in
231 fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<T, F>
232 where F: FnMut(&T) -> bool;
234 /// Returns an iterator over all contiguous windows of length
235 /// `size`. The windows overlap. If the slice is shorter than
236 /// `size`, the iterator returns no values.
240 /// Panics if `size` is 0.
244 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
248 /// let v = &[1, 2, 3, 4];
249 /// for win in v.windows(2) {
250 /// println!("{}", win);
254 fn windows(&self, size: uint) -> Windows<T>;
256 /// Returns an iterator over `size` elements of the slice at a
257 /// time. The chunks do not overlap. If `size` does not divide the
258 /// length of the slice, then the last chunk will not have length
263 /// Panics if `size` is 0.
267 /// Print the slice two elements at a time (i.e. `[1,2]`,
271 /// let v = &[1, 2, 3, 4, 5];
272 /// for win in v.chunks(2) {
273 /// println!("{}", win);
277 fn chunks(&self, size: uint) -> Chunks<T>;
279 /// Returns the element of a slice at the given index, or `None` if the
280 /// index is out of bounds.
282 fn get(&self, index: uint) -> Option<&T>;
284 /// Returns the first element of a slice, or `None` if it is empty.
286 fn first(&self) -> Option<&T>;
288 /// Deprecated: renamed to `first`.
289 #[deprecated = "renamed to `first`"]
290 fn head(&self) -> Option<&T> { self.first() }
292 /// Returns all but the first element of a slice.
293 #[experimental = "likely to be renamed"]
294 fn tail(&self) -> &[T];
296 /// Returns all but the last element of a slice.
297 #[experimental = "likely to be renamed"]
298 fn init(&self) -> &[T];
300 /// Returns the last element of a slice, or `None` if it is empty.
302 fn last(&self) -> Option<&T>;
304 /// Returns a pointer to the element at the given index, without doing
307 unsafe fn get_unchecked(&self, index: uint) -> &T;
309 /// Deprecated: renamed to `get_unchecked`.
310 #[deprecated = "renamed to get_unchecked"]
311 unsafe fn unsafe_get(&self, index: uint) -> &T {
312 self.get_unchecked(index)
315 /// Returns an unsafe pointer to the slice's buffer
317 /// The caller must ensure that the slice outlives the pointer this
318 /// function returns, or else it will end up pointing to garbage.
320 /// Modifying the slice may cause its buffer to be reallocated, which
321 /// would also make any pointers to it invalid.
323 fn as_ptr(&self) -> *const T;
325 /// Binary search a sorted slice with a comparator function.
327 /// The comparator function should implement an order consistent
328 /// with the sort order of the underlying slice, returning an
329 /// order code that indicates whether its argument is `Less`,
330 /// `Equal` or `Greater` the desired target.
332 /// If a matching value is found then returns `Ok`, containing
333 /// the index for the matched element; if no match is found then
334 /// `Err` is returned, containing the index where a matching
335 /// element could be inserted while maintaining sorted order.
339 /// Looks up a series of four elements. The first is found, with a
340 /// uniquely determined position; the second and third are not
341 /// found; the fourth could match any position in `[1,4]`.
344 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
345 /// let s = s.as_slice();
348 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
350 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
352 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
354 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
355 /// assert!(match r { Ok(1...4) => true, _ => false, });
358 fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
359 F: FnMut(&T) -> Ordering;
361 /// Return the number of elements in the slice
366 /// let a = [1, 2, 3];
367 /// assert_eq!(a.len(), 3);
370 fn len(&self) -> uint;
372 /// Returns true if the slice has a length of 0
377 /// let a = [1, 2, 3];
378 /// assert!(!a.is_empty());
382 fn is_empty(&self) -> bool { self.len() == 0 }
383 /// Returns a mutable reference to the element at the given index,
384 /// or `None` if the index is out of bounds
386 fn get_mut(&mut self, index: uint) -> Option<&mut T>;
388 /// Work with `self` as a mut slice.
389 /// Primarily intended for getting a &mut [T] from a [T; N].
391 fn as_mut_slice(&mut self) -> &mut [T];
393 /// Returns a mutable subslice spanning the interval [`start`, `end`).
395 /// Panics when the end of the new slice lies beyond the end of the
396 /// original slice (i.e. when `end > self.len()`) or when `start > end`.
398 /// Slicing with `start` equal to `end` yields an empty slice.
399 #[experimental = "will be replaced by slice syntax"]
400 fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T];
402 /// Returns a mutable subslice from `start` to the end of the slice.
404 /// Panics when `start` is strictly greater than the length of the original slice.
406 /// Slicing from `self.len()` yields an empty slice.
407 #[experimental = "will be replaced by slice syntax"]
408 fn slice_from_mut(&mut self, start: uint) -> &mut [T];
410 /// Returns a mutable subslice from the start of the slice to `end`.
412 /// Panics when `end` is strictly greater than the length of the original slice.
414 /// Slicing to `0` yields an empty slice.
415 #[experimental = "will be replaced by slice syntax"]
416 fn slice_to_mut(&mut self, end: uint) -> &mut [T];
418 /// Returns an iterator that allows modifying each value
420 fn iter_mut(&mut self) -> IterMut<T>;
422 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
424 fn first_mut(&mut self) -> Option<&mut T>;
426 /// Depreated: renamed to `first_mut`.
427 #[deprecated = "renamed to first_mut"]
428 fn head_mut(&mut self) -> Option<&mut T> {
432 /// Returns all but the first element of a mutable slice
433 #[experimental = "likely to be renamed or removed"]
434 fn tail_mut(&mut self) -> &mut [T];
436 /// Returns all but the last element of a mutable slice
437 #[experimental = "likely to be renamed or removed"]
438 fn init_mut(&mut self) -> &mut [T];
440 /// Returns a mutable pointer to the last item in the slice.
442 fn last_mut(&mut self) -> Option<&mut T>;
444 /// Returns an iterator over mutable subslices separated by elements that
445 /// match `pred`. The matched element is not contained in the subslices.
447 fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
448 where F: FnMut(&T) -> bool;
450 /// Returns an iterator over subslices separated by elements that match
451 /// `pred`, limited to splitting at most `n` times. The matched element is
452 /// not contained in the subslices.
454 fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<T, F>
455 where F: FnMut(&T) -> bool;
457 /// Returns an iterator over subslices separated by elements that match
458 /// `pred` limited to splitting at most `n` times. This starts at the end of
459 /// the slice and works backwards. The matched element is not contained in
462 fn rsplitn_mut<F>(&mut self, n: uint, pred: F) -> RSplitNMut<T, F>
463 where F: FnMut(&T) -> bool;
465 /// Returns an iterator over `chunk_size` elements of the slice at a time.
466 /// The chunks are mutable and do not overlap. If `chunk_size` does
467 /// not divide the length of the slice, then the last chunk will not
468 /// have length `chunk_size`.
472 /// Panics if `chunk_size` is 0.
474 fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<T>;
476 /// Swaps two elements in a slice.
480 /// * a - The index of the first element
481 /// * b - The index of the second element
485 /// Panics if `a` or `b` are out of bounds.
490 /// let mut v = ["a", "b", "c", "d"];
492 /// assert!(v == ["a", "d", "c", "b"]);
495 fn swap(&mut self, a: uint, b: uint);
497 /// Divides one `&mut` into two at an index.
499 /// The first will contain all indices from `[0, mid)` (excluding
500 /// the index `mid` itself) and the second will contain all
501 /// indices from `[mid, len)` (excluding the index `len` itself).
505 /// Panics if `mid > len`.
510 /// let mut v = [1, 2, 3, 4, 5, 6];
512 /// // scoped to restrict the lifetime of the borrows
514 /// let (left, right) = v.split_at_mut(0);
515 /// assert!(left == []);
516 /// assert!(right == [1, 2, 3, 4, 5, 6]);
520 /// let (left, right) = v.split_at_mut(2);
521 /// assert!(left == [1, 2]);
522 /// assert!(right == [3, 4, 5, 6]);
526 /// let (left, right) = v.split_at_mut(6);
527 /// assert!(left == [1, 2, 3, 4, 5, 6]);
528 /// assert!(right == []);
532 fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]);
534 /// Reverse the order of elements in a slice, in place.
539 /// let mut v = [1, 2, 3];
541 /// assert!(v == [3, 2, 1]);
544 fn reverse(&mut self);
546 /// Returns an unsafe mutable pointer to the element in index
548 unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T;
550 /// Deprecated: renamed to `get_unchecked_mut`.
551 #[deprecated = "renamed to get_unchecked_mut"]
552 unsafe fn unchecked_mut(&mut self, index: uint) -> &mut T {
553 self.get_unchecked_mut(index)
556 /// Return an unsafe mutable pointer to the slice's buffer.
558 /// The caller must ensure that the slice outlives the pointer this
559 /// function returns, or else it will end up pointing to garbage.
561 /// Modifying the slice may cause its buffer to be reallocated, which
562 /// would also make any pointers to it invalid.
565 fn as_mut_ptr(&mut self) -> *mut T;
569 impl<T> SliceExt for [T] {
573 fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
574 merge_sort(self, compare)
578 fn move_from(&mut self, mut src: Vec<T>, start: uint, end: uint) -> uint {
579 for (a, b) in self.iter_mut().zip(src.slice_mut(start, end).iter_mut()) {
582 cmp::min(self.len(), end-start)
586 fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
587 core_slice::SliceExt::slice(self, start, end)
591 fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
592 core_slice::SliceExt::slice_from(self, start)
596 fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
597 core_slice::SliceExt::slice_to(self, end)
601 fn split_at<'a>(&'a self, mid: uint) -> (&'a [T], &'a [T]) {
602 core_slice::SliceExt::split_at(self, mid)
606 fn iter<'a>(&'a self) -> Iter<'a, T> {
607 core_slice::SliceExt::iter(self)
611 fn split<F>(&self, pred: F) -> Split<T, F>
612 where F: FnMut(&T) -> bool {
613 core_slice::SliceExt::split(self, pred)
617 fn splitn<F>(&self, n: uint, pred: F) -> SplitN<T, F>
618 where F: FnMut(&T) -> bool {
619 core_slice::SliceExt::splitn(self, n, pred)
623 fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<T, F>
624 where F: FnMut(&T) -> bool {
625 core_slice::SliceExt::rsplitn(self, n, pred)
629 fn windows<'a>(&'a self, size: uint) -> Windows<'a, T> {
630 core_slice::SliceExt::windows(self, size)
634 fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, T> {
635 core_slice::SliceExt::chunks(self, size)
639 fn get<'a>(&'a self, index: uint) -> Option<&'a T> {
640 core_slice::SliceExt::get(self, index)
644 fn first<'a>(&'a self) -> Option<&'a T> {
645 core_slice::SliceExt::first(self)
649 fn tail<'a>(&'a self) -> &'a [T] {
650 core_slice::SliceExt::tail(self)
654 fn init<'a>(&'a self) -> &'a [T] {
655 core_slice::SliceExt::init(self)
659 fn last<'a>(&'a self) -> Option<&'a T> {
660 core_slice::SliceExt::last(self)
664 unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a T {
665 core_slice::SliceExt::get_unchecked(self, index)
669 fn as_ptr(&self) -> *const T {
670 core_slice::SliceExt::as_ptr(self)
674 fn binary_search_by<F>(&self, f: F) -> Result<uint, uint>
675 where F: FnMut(&T) -> Ordering {
676 core_slice::SliceExt::binary_search_by(self, f)
680 fn len(&self) -> uint {
681 core_slice::SliceExt::len(self)
685 fn is_empty(&self) -> bool {
686 core_slice::SliceExt::is_empty(self)
690 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> {
691 core_slice::SliceExt::get_mut(self, index)
695 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
696 core_slice::SliceExt::as_mut_slice(self)
700 fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T] {
701 core_slice::SliceExt::slice_mut(self, start, end)
705 fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T] {
706 core_slice::SliceExt::slice_from_mut(self, start)
710 fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T] {
711 core_slice::SliceExt::slice_to_mut(self, end)
715 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
716 core_slice::SliceExt::iter_mut(self)
720 fn first_mut<'a>(&'a mut self) -> Option<&'a mut T> {
721 core_slice::SliceExt::first_mut(self)
725 fn tail_mut<'a>(&'a mut self) -> &'a mut [T] {
726 core_slice::SliceExt::tail_mut(self)
730 fn init_mut<'a>(&'a mut self) -> &'a mut [T] {
731 core_slice::SliceExt::init_mut(self)
735 fn last_mut<'a>(&'a mut self) -> Option<&'a mut T> {
736 core_slice::SliceExt::last_mut(self)
740 fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
741 where F: FnMut(&T) -> bool {
742 core_slice::SliceExt::split_mut(self, pred)
746 fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<T, F>
747 where F: FnMut(&T) -> bool {
748 core_slice::SliceExt::splitn_mut(self, n, pred)
752 fn rsplitn_mut<F>(&mut self, n: uint, pred: F) -> RSplitNMut<T, F>
753 where F: FnMut(&T) -> bool {
754 core_slice::SliceExt::rsplitn_mut(self, n, pred)
758 fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, T> {
759 core_slice::SliceExt::chunks_mut(self, chunk_size)
763 fn swap(&mut self, a: uint, b: uint) {
764 core_slice::SliceExt::swap(self, a, b)
768 fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
769 core_slice::SliceExt::split_at_mut(self, mid)
773 fn reverse(&mut self) {
774 core_slice::SliceExt::reverse(self)
778 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
779 core_slice::SliceExt::get_unchecked_mut(self, index)
783 fn as_mut_ptr(&mut self) -> *mut T {
784 core_slice::SliceExt::as_mut_ptr(self)
788 ////////////////////////////////////////////////////////////////////////////////
789 // Extension traits for slices over specifc kinds of data
790 ////////////////////////////////////////////////////////////////////////////////
792 /// Extension methods for boxed slices.
793 #[experimental = "likely to merge into SliceExt if it survives"]
794 pub trait BoxedSliceExt<T> {
795 /// Convert `self` into a vector without clones or allocation.
797 fn into_vec(self) -> Vec<T>;
800 #[experimental = "trait is experimental"]
801 impl<T> BoxedSliceExt<T> for Box<[T]> {
802 fn into_vec(mut self) -> Vec<T> {
804 let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len());
811 /// Allocating extension methods for slices containing `Clone` elements.
812 #[unstable = "likely to be merged into SliceExt"]
813 pub trait CloneSliceExt<T> for Sized? {
814 /// Copies `self` into a new `Vec`.
816 fn to_vec(&self) -> Vec<T>;
818 /// Deprecated: use `iter().cloned().partition(f)` instead.
819 #[deprecated = "use iter().cloned().partition(f) instead"]
820 fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool;
822 /// Creates an iterator that yields every possible permutation of the
823 /// vector in succession.
828 /// let v = [1, 2, 3];
829 /// let mut perms = v.permutations();
832 /// println!("{}", p);
836 /// Iterating through permutations one by one.
839 /// let v = [1, 2, 3];
840 /// let mut perms = v.permutations();
842 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
843 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
844 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
847 fn permutations(&self) -> Permutations<T>;
849 /// Copies as many elements from `src` as it can into `self` (the
850 /// shorter of `self.len()` and `src.len()`). Returns the number
851 /// of elements copied.
856 /// let mut dst = [0, 0, 0];
857 /// let src = [1, 2];
859 /// assert!(dst.clone_from_slice(&src) == 2);
860 /// assert!(dst == [1, 2, 0]);
862 /// let src2 = [3, 4, 5, 6];
863 /// assert!(dst.clone_from_slice(&src2) == 3);
864 /// assert!(dst == [3, 4, 5]);
867 fn clone_from_slice(&mut self, &[T]) -> uint;
871 #[unstable = "trait is unstable"]
872 impl<T: Clone> CloneSliceExt<T> for [T] {
873 /// Returns a copy of `v`.
875 fn to_vec(&self) -> Vec<T> {
876 let mut vector = Vec::with_capacity(self.len());
877 vector.push_all(self);
883 fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool {
884 self.iter().cloned().partition(f)
887 /// Returns an iterator over all permutations of a vector.
888 fn permutations(&self) -> Permutations<T> {
890 swaps: ElementSwaps::new(self.len()),
895 fn clone_from_slice(&mut self, src: &[T]) -> uint {
896 core_slice::CloneSliceExt::clone_from_slice(self, src)
900 /// Allocating extension methods for slices on Ord values.
901 #[unstable = "likely to merge with SliceExt"]
902 pub trait OrdSliceExt<T> for Sized? {
903 /// Sorts the slice, in place.
905 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
910 /// let mut v = [-5, 4, 1, -3, 2];
913 /// assert!(v == [-5, -3, 1, 2, 4]);
918 /// Binary search a sorted slice for a given element.
920 /// If the value is found then `Ok` is returned, containing the
921 /// index of the matching element; if the value is not found then
922 /// `Err` is returned, containing the index where a matching
923 /// element could be inserted while maintaining sorted order.
927 /// Looks up a series of four elements. The first is found, with a
928 /// uniquely determined position; the second and third are not
929 /// found; the fourth could match any position in `[1,4]`.
932 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
933 /// let s = s.as_slice();
935 /// assert_eq!(s.binary_search(&13), Ok(9));
936 /// assert_eq!(s.binary_search(&4), Err(7));
937 /// assert_eq!(s.binary_search(&100), Err(13));
938 /// let r = s.binary_search(&1);
939 /// assert!(match r { Ok(1...4) => true, _ => false, });
942 fn binary_search(&self, x: &T) -> Result<uint, uint>;
944 /// Deprecated: use `binary_search` instead.
945 #[deprecated = "use binary_search instead"]
946 fn binary_search_elem(&self, x: &T) -> Result<uint, uint> {
947 self.binary_search(x)
950 /// Mutates the slice to the next lexicographic permutation.
952 /// Returns `true` if successful and `false` if the slice is at the
953 /// last-ordered permutation.
958 /// let v: &mut [_] = &mut [0, 1, 2];
959 /// v.next_permutation();
960 /// let b: &mut [_] = &mut [0, 2, 1];
962 /// v.next_permutation();
963 /// let b: &mut [_] = &mut [1, 0, 2];
966 #[unstable = "uncertain if this merits inclusion in std"]
967 fn next_permutation(&mut self) -> bool;
969 /// Mutates the slice to the previous lexicographic permutation.
971 /// Returns `true` if successful and `false` if the slice is at the
972 /// first-ordered permutation.
977 /// let v: &mut [_] = &mut [1, 0, 2];
978 /// v.prev_permutation();
979 /// let b: &mut [_] = &mut [0, 2, 1];
981 /// v.prev_permutation();
982 /// let b: &mut [_] = &mut [0, 1, 2];
985 #[unstable = "uncertain if this merits inclusion in std"]
986 fn prev_permutation(&mut self) -> bool;
989 #[unstable = "trait is unstable"]
990 impl<T: Ord> OrdSliceExt<T> for [T] {
993 self.sort_by(|a, b| a.cmp(b))
996 fn binary_search(&self, x: &T) -> Result<uint, uint> {
997 core_slice::OrdSliceExt::binary_search(self, x)
1000 fn next_permutation(&mut self) -> bool {
1001 core_slice::OrdSliceExt::next_permutation(self)
1004 fn prev_permutation(&mut self) -> bool {
1005 core_slice::OrdSliceExt::prev_permutation(self)
1009 #[unstable = "U should be an associated type"]
1010 /// An extension trait for concatenating slices
1011 pub trait SliceConcatExt<T: ?Sized, U> {
1012 /// Flattens a slice of `T` into a single value `U`.
1014 fn concat(&self) -> U;
1016 #[deprecated = "renamed to concat"]
1017 fn concat_vec(&self) -> U {
1021 /// Flattens a slice of `T` into a single value `U`, placing a
1022 /// given seperator between each.
1024 fn connect(&self, sep: &T) -> U;
1026 #[deprecated = "renamed to connect"]
1027 fn connect_vec(&self, sep: &T) -> U {
1032 impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
1033 fn concat(&self) -> Vec<T> {
1034 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
1035 let mut result = Vec::with_capacity(size);
1036 for v in self.iter() {
1037 result.push_all(v.as_slice())
1042 fn connect(&self, sep: &T) -> Vec<T> {
1043 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
1044 let mut result = Vec::with_capacity(size + self.len());
1045 let mut first = true;
1046 for v in self.iter() {
1047 if first { first = false } else { result.push(sep.clone()) }
1048 result.push_all(v.as_slice())
1054 /// An iterator that yields the element swaps needed to produce
1055 /// a sequence of all possible permutations for an indexed sequence of
1056 /// elements. Each permutation is only a single swap apart.
1058 /// The Steinhaus-Johnson-Trotter algorithm is used.
1060 /// Generates even and odd permutations alternately.
1062 /// The last generated swap is always (0, 1), and it returns the
1063 /// sequence to its initial order.
1066 pub struct ElementSwaps {
1067 sdir: Vec<SizeDirection>,
1068 /// If `true`, emit the last swap that returns the sequence to initial
1075 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1077 pub fn new(length: uint) -> ElementSwaps {
1078 // Initialize `sdir` with a direction that position should move in
1079 // (all negative at the beginning) and the `size` of the
1080 // element (equal to the original index).
1083 sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1089 ////////////////////////////////////////////////////////////////////////////////
1090 // Standard trait implementations for slices
1091 ////////////////////////////////////////////////////////////////////////////////
1093 #[unstable = "trait is unstable"]
1094 impl<T> BorrowFrom<Vec<T>> for [T] {
1095 fn borrow_from(owned: &Vec<T>) -> &[T] { owned[] }
1098 #[unstable = "trait is unstable"]
1099 impl<T> BorrowFromMut<Vec<T>> for [T] {
1100 fn borrow_from_mut(owned: &mut Vec<T>) -> &mut [T] { owned.as_mut_slice_() }
1103 #[unstable = "trait is unstable"]
1104 impl<T: Clone> ToOwned<Vec<T>> for [T] {
1105 fn to_owned(&self) -> Vec<T> { self.to_vec() }
1108 ////////////////////////////////////////////////////////////////////////////////
1110 ////////////////////////////////////////////////////////////////////////////////
1112 #[deriving(Copy, Clone)]
1113 enum Direction { Pos, Neg }
1115 /// An `Index` and `Direction` together.
1116 #[deriving(Copy, Clone)]
1117 struct SizeDirection {
1123 impl Iterator for ElementSwaps {
1124 type Item = (uint, uint);
1127 fn next(&mut self) -> Option<(uint, uint)> {
1128 fn new_pos(i: uint, s: Direction) -> uint {
1129 i + match s { Pos => 1, Neg => -1 }
1132 // Find the index of the largest mobile element:
1133 // The direction should point into the vector, and the
1134 // swap should be with a smaller `size` element.
1135 let max = self.sdir.iter().map(|&x| x).enumerate()
1137 new_pos(i, sd.dir) < self.sdir.len() &&
1138 self.sdir[new_pos(i, sd.dir)].size < sd.size)
1139 .max_by(|&(_, sd)| sd.size);
1142 let j = new_pos(i, sd.dir);
1143 self.sdir.swap(i, j);
1145 // Swap the direction of each larger SizeDirection
1146 for x in self.sdir.iter_mut() {
1147 if x.size > sd.size {
1148 x.dir = match x.dir { Pos => Neg, Neg => Pos };
1151 self.swaps_made += 1;
1154 None => if self.emit_reset {
1155 self.emit_reset = false;
1156 if self.sdir.len() > 1 {
1158 self.swaps_made += 1;
1161 // Vector is of the form [] or [x], and the only permutation is itself
1162 self.swaps_made += 1;
1170 fn size_hint(&self) -> (uint, Option<uint>) {
1171 // For a vector of size n, there are exactly n! permutations.
1172 let n = range(2, self.sdir.len() + 1).product();
1173 (n - self.swaps_made, Some(n - self.swaps_made))
1177 /// An iterator that uses `ElementSwaps` to iterate through
1178 /// all possible permutations of a vector.
1180 /// The first iteration yields a clone of the vector as it is,
1181 /// then each successive element is the vector with one
1184 /// Generates even and odd permutations alternately.
1186 pub struct Permutations<T> {
1187 swaps: ElementSwaps,
1191 #[unstable = "trait is unstable"]
1192 impl<T: Clone> Iterator<Vec<T>> for Permutations<T> {
1194 fn next(&mut self) -> Option<Vec<T>> {
1195 match self.swaps.next() {
1197 Some((0,0)) => Some(self.v.clone()),
1199 let elt = self.v.clone();
1207 fn size_hint(&self) -> (uint, Option<uint>) {
1208 self.swaps.size_hint()
1212 ////////////////////////////////////////////////////////////////////////////////
1214 ////////////////////////////////////////////////////////////////////////////////
1216 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1217 let len = v.len() as int;
1218 let buf_v = v.as_mut_ptr();
1221 for i in range(1, len) {
1222 // j satisfies: 0 <= j <= i;
1225 // `i` is in bounds.
1226 let read_ptr = buf_v.offset(i) as *const T;
1228 // find where to insert, we need to do strict <,
1229 // rather than <=, to maintain stability.
1231 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1233 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1237 // shift everything to the right, to make space to
1238 // insert this value.
1240 // j + 1 could be `len` (for the last `i`), but in
1241 // that case, `i == j` so we don't copy. The
1242 // `.offset(j)` is always in bounds.
1245 let tmp = ptr::read(read_ptr);
1246 ptr::copy_memory(buf_v.offset(j + 1),
1249 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
1258 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1259 // warning: this wildly uses unsafe.
1260 static BASE_INSERTION: uint = 32;
1261 static LARGE_INSERTION: uint = 16;
1263 // FIXME #12092: smaller insertion runs seems to make sorting
1264 // vectors of large elements a little faster on some platforms,
1265 // but hasn't been tested/tuned extensively
1266 let insertion = if size_of::<T>() <= 16 {
1274 // short vectors get sorted in-place via insertion sort to avoid allocations
1275 if len <= insertion {
1276 insertion_sort(v, compare);
1280 // allocate some memory to use as scratch memory, we keep the
1281 // length 0 so we can keep shallow copies of the contents of `v`
1282 // without risking the dtors running on an object twice if
1283 // `compare` panics.
1284 let mut working_space = Vec::with_capacity(2 * len);
1285 // these both are buffers of length `len`.
1286 let mut buf_dat = working_space.as_mut_ptr();
1287 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
1290 let buf_v = v.as_ptr();
1292 // step 1. sort short runs with insertion sort. This takes the
1293 // values from `v` and sorts them into `buf_dat`, leaving that
1294 // with sorted runs of length INSERTION.
1296 // We could hardcode the sorting comparisons here, and we could
1297 // manipulate/step the pointers themselves, rather than repeatedly
1299 for start in range_step(0, len, insertion) {
1300 // start <= i < len;
1301 for i in range(start, cmp::min(start + insertion, len)) {
1302 // j satisfies: start <= j <= i;
1303 let mut j = i as int;
1305 // `i` is in bounds.
1306 let read_ptr = buf_v.offset(i as int);
1308 // find where to insert, we need to do strict <,
1309 // rather than <=, to maintain stability.
1311 // start <= j - 1 < len, so .offset(j - 1) is in
1313 while j > start as int &&
1314 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1318 // shift everything to the right, to make space to
1319 // insert this value.
1321 // j + 1 could be `len` (for the last `i`), but in
1322 // that case, `i == j` so we don't copy. The
1323 // `.offset(j)` is always in bounds.
1324 ptr::copy_memory(buf_dat.offset(j + 1),
1325 &*buf_dat.offset(j),
1327 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1332 // step 2. merge the sorted runs.
1333 let mut width = insertion;
1335 // merge the sorted runs of length `width` in `buf_dat` two at
1336 // a time, placing the result in `buf_tmp`.
1338 // 0 <= start <= len.
1339 for start in range_step(0, len, 2 * width) {
1340 // manipulate pointers directly for speed (rather than
1341 // using a `for` loop with `range` and `.offset` inside
1344 // the end of the first run & start of the
1345 // second. Offset of `len` is defined, since this is
1346 // precisely one byte past the end of the object.
1347 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
1348 // end of the second. Similar reasoning to the above re safety.
1349 let right_end_idx = cmp::min(start + 2 * width, len);
1350 let right_end = buf_dat.offset(right_end_idx as int);
1352 // the pointers to the elements under consideration
1353 // from the two runs.
1355 // both of these are in bounds.
1356 let mut left = buf_dat.offset(start as int);
1357 let mut right = right_start;
1359 // where we're putting the results, it is a run of
1360 // length `2*width`, so we step it once for each step
1361 // of either `left` or `right`. `buf_tmp` has length
1362 // `len`, so these are in bounds.
1363 let mut out = buf_tmp.offset(start as int);
1364 let out_end = buf_tmp.offset(right_end_idx as int);
1366 while out < out_end {
1367 // Either the left or the right run are exhausted,
1368 // so just copy the remainder from the other run
1369 // and move on; this gives a huge speed-up (order
1370 // of 25%) for mostly sorted vectors (the best
1372 if left == right_start {
1373 // the number remaining in this run.
1374 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
1375 ptr::copy_nonoverlapping_memory(out, &*right, elems);
1377 } else if right == right_end {
1378 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
1379 ptr::copy_nonoverlapping_memory(out, &*left, elems);
1383 // check which side is smaller, and that's the
1384 // next element for the new run.
1386 // `left < right_start` and `right < right_end`,
1387 // so these are valid.
1388 let to_copy = if compare(&*left, &*right) == Greater {
1393 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
1399 mem::swap(&mut buf_dat, &mut buf_tmp);
1404 // write the result to `v` in one go, so that there are never two copies
1405 // of the same object in `v`.
1407 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
1410 // increment the pointer, returning the old pointer.
1412 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1414 *ptr = ptr.offset(1);
1419 /// Deprecated, unsafe operations
1422 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
1423 pub use core::slice::raw::{shift_ptr, pop_ptr};
1428 use std::boxed::Box;
1429 use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal};
1430 use prelude::{SliceExt, Iterator, IteratorExt, DoubleEndedIteratorExt};
1431 use prelude::{OrdSliceExt, CloneSliceExt, PartialEqSliceExt, AsSlice};
1432 use prelude::{RandomAccessIterator, Ord, SliceConcatExt};
1433 use core::cell::Cell;
1434 use core::default::Default;
1436 use std::rand::{Rng, thread_rng};
1438 use super::ElementSwaps;
1440 fn square(n: uint) -> uint { n * n }
1442 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
1446 // Test on-stack from_fn.
1447 let mut v = Vec::from_fn(3u, square);
1449 let v = v.as_slice();
1450 assert_eq!(v.len(), 3u);
1451 assert_eq!(v[0], 0u);
1452 assert_eq!(v[1], 1u);
1453 assert_eq!(v[2], 4u);
1456 // Test on-heap from_fn.
1457 v = Vec::from_fn(5u, square);
1459 let v = v.as_slice();
1460 assert_eq!(v.len(), 5u);
1461 assert_eq!(v[0], 0u);
1462 assert_eq!(v[1], 1u);
1463 assert_eq!(v[2], 4u);
1464 assert_eq!(v[3], 9u);
1465 assert_eq!(v[4], 16u);
1470 fn test_from_elem() {
1471 // Test on-stack from_elem.
1472 let mut v = Vec::from_elem(2u, 10u);
1474 let v = v.as_slice();
1475 assert_eq!(v.len(), 2u);
1476 assert_eq!(v[0], 10u);
1477 assert_eq!(v[1], 10u);
1480 // Test on-heap from_elem.
1481 v = Vec::from_elem(6u, 20u);
1483 let v = v.as_slice();
1484 assert_eq!(v[0], 20u);
1485 assert_eq!(v[1], 20u);
1486 assert_eq!(v[2], 20u);
1487 assert_eq!(v[3], 20u);
1488 assert_eq!(v[4], 20u);
1489 assert_eq!(v[5], 20u);
1494 fn test_is_empty() {
1495 let xs: [int; 0] = [];
1496 assert!(xs.is_empty());
1497 assert!(![0i].is_empty());
1501 fn test_len_divzero() {
1503 let v0 : &[Z] = &[];
1504 let v1 : &[Z] = &[[]];
1505 let v2 : &[Z] = &[[], []];
1506 assert_eq!(mem::size_of::<Z>(), 0);
1507 assert_eq!(v0.len(), 0);
1508 assert_eq!(v1.len(), 1);
1509 assert_eq!(v2.len(), 2);
1514 let mut a = vec![11i];
1515 assert_eq!(a.as_slice().get(1), None);
1517 assert_eq!(a.as_slice().get(1).unwrap(), &12);
1518 a = vec![11i, 12, 13];
1519 assert_eq!(a.as_slice().get(1).unwrap(), &12);
1525 assert_eq!(a.as_slice().head(), None);
1527 assert_eq!(a.as_slice().head().unwrap(), &11);
1529 assert_eq!(a.as_slice().head().unwrap(), &11);
1533 fn test_head_mut() {
1535 assert_eq!(a.head_mut(), None);
1537 assert_eq!(*a.head_mut().unwrap(), 11);
1539 assert_eq!(*a.head_mut().unwrap(), 11);
1544 let mut a = vec![11i];
1545 let b: &[int] = &[];
1546 assert_eq!(a.tail(), b);
1548 let b: &[int] = &[12];
1549 assert_eq!(a.tail(), b);
1553 fn test_tail_mut() {
1554 let mut a = vec![11i];
1555 let b: &mut [int] = &mut [];
1556 assert!(a.tail_mut() == b);
1558 let b: &mut [int] = &mut [12];
1559 assert!(a.tail_mut() == b);
1564 fn test_tail_empty() {
1565 let a: Vec<int> = vec![];
1571 fn test_tail_mut_empty() {
1572 let mut a: Vec<int> = vec![];
1578 let mut a = vec![11i];
1579 let b: &[int] = &[];
1580 assert_eq!(a.init(), b);
1582 let b: &[int] = &[11];
1583 assert_eq!(a.init(), b);
1587 fn test_init_mut() {
1588 let mut a = vec![11i];
1589 let b: &mut [int] = &mut [];
1590 assert!(a.init_mut() == b);
1592 let b: &mut [int] = &mut [11];
1593 assert!(a.init_mut() == b);
1598 fn test_init_empty() {
1599 let a: Vec<int> = vec![];
1605 fn test_init_mut_empty() {
1606 let mut a: Vec<int> = vec![];
1613 assert_eq!(a.as_slice().last(), None);
1615 assert_eq!(a.as_slice().last().unwrap(), &11);
1617 assert_eq!(a.as_slice().last().unwrap(), &12);
1621 fn test_last_mut() {
1623 assert_eq!(a.last_mut(), None);
1625 assert_eq!(*a.last_mut().unwrap(), 11);
1627 assert_eq!(*a.last_mut().unwrap(), 12);
1632 // Test fixed length vector.
1633 let vec_fixed = [1i, 2, 3, 4];
1634 let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
1635 assert_eq!(v_a.len(), 3u);
1636 let v_a = v_a.as_slice();
1637 assert_eq!(v_a[0], 2);
1638 assert_eq!(v_a[1], 3);
1639 assert_eq!(v_a[2], 4);
1642 let vec_stack: &[_] = &[1i, 2, 3];
1643 let v_b = vec_stack[1u..3u].to_vec();
1644 assert_eq!(v_b.len(), 2u);
1645 let v_b = v_b.as_slice();
1646 assert_eq!(v_b[0], 2);
1647 assert_eq!(v_b[1], 3);
1650 let vec_unique = vec![1i, 2, 3, 4, 5, 6];
1651 let v_d = vec_unique[1u..6u].to_vec();
1652 assert_eq!(v_d.len(), 5u);
1653 let v_d = v_d.as_slice();
1654 assert_eq!(v_d[0], 2);
1655 assert_eq!(v_d[1], 3);
1656 assert_eq!(v_d[2], 4);
1657 assert_eq!(v_d[3], 5);
1658 assert_eq!(v_d[4], 6);
1662 fn test_slice_from() {
1663 let vec: &[int] = &[1, 2, 3, 4];
1664 assert_eq!(vec[0..], vec);
1665 let b: &[int] = &[3, 4];
1666 assert_eq!(vec[2..], b);
1667 let b: &[int] = &[];
1668 assert_eq!(vec[4..], b);
1672 fn test_slice_to() {
1673 let vec: &[int] = &[1, 2, 3, 4];
1674 assert_eq!(vec[..4], vec);
1675 let b: &[int] = &[1, 2];
1676 assert_eq!(vec[..2], b);
1677 let b: &[int] = &[];
1678 assert_eq!(vec[..0], b);
1684 let mut v = vec![5i];
1686 assert_eq!(v.len(), 0);
1687 assert_eq!(e, Some(5));
1689 assert_eq!(f, None);
1691 assert_eq!(g, None);
1695 fn test_swap_remove() {
1696 let mut v = vec![1i, 2, 3, 4, 5];
1697 let mut e = v.swap_remove(0);
1699 assert_eq!(v, vec![5i, 2, 3, 4]);
1700 e = v.swap_remove(3);
1702 assert_eq!(v, vec![5i, 2, 3]);
1707 fn test_swap_remove_fail() {
1708 let mut v = vec![1i];
1709 let _ = v.swap_remove(0);
1710 let _ = v.swap_remove(0);
1714 fn test_swap_remove_noncopyable() {
1715 // Tests that we don't accidentally run destructors twice.
1716 let mut v = Vec::new();
1720 let mut _e = v.swap_remove(0);
1721 assert_eq!(v.len(), 2);
1722 _e = v.swap_remove(1);
1723 assert_eq!(v.len(), 1);
1724 _e = v.swap_remove(0);
1725 assert_eq!(v.len(), 0);
1730 // Test on-stack push().
1733 assert_eq!(v.len(), 1u);
1734 assert_eq!(v.as_slice()[0], 1);
1736 // Test on-heap push().
1738 assert_eq!(v.len(), 2u);
1739 assert_eq!(v.as_slice()[0], 1);
1740 assert_eq!(v.as_slice()[1], 2);
1745 // Test on-stack grow().
1749 let v = v.as_slice();
1750 assert_eq!(v.len(), 2u);
1751 assert_eq!(v[0], 1);
1752 assert_eq!(v[1], 1);
1755 // Test on-heap grow().
1758 let v = v.as_slice();
1759 assert_eq!(v.len(), 5u);
1760 assert_eq!(v[0], 1);
1761 assert_eq!(v[1], 1);
1762 assert_eq!(v[2], 2);
1763 assert_eq!(v[3], 2);
1764 assert_eq!(v[4], 2);
1771 v.grow_fn(3u, square);
1772 let v = v.as_slice();
1773 assert_eq!(v.len(), 3u);
1774 assert_eq!(v[0], 0u);
1775 assert_eq!(v[1], 1u);
1776 assert_eq!(v[2], 4u);
1780 fn test_truncate() {
1781 let mut v = vec![box 6i,box 5,box 4];
1783 let v = v.as_slice();
1784 assert_eq!(v.len(), 1);
1785 assert_eq!(*(v[0]), 6);
1786 // If the unsafe block didn't drop things properly, we blow up here.
1791 let mut v = vec![box 6i,box 5,box 4];
1793 assert_eq!(v.len(), 0);
1794 // If the unsafe block didn't drop things properly, we blow up here.
1799 fn case(a: Vec<uint>, b: Vec<uint>) {
1804 case(vec![], vec![]);
1805 case(vec![1u], vec![1]);
1806 case(vec![1u,1], vec![1]);
1807 case(vec![1u,2,3], vec![1,2,3]);
1808 case(vec![1u,1,2,3], vec![1,2,3]);
1809 case(vec![1u,2,2,3], vec![1,2,3]);
1810 case(vec![1u,2,3,3], vec![1,2,3]);
1811 case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1815 fn test_dedup_unique() {
1816 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1818 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1820 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1823 * If the boxed pointers were leaked or otherwise misused, valgrind
1824 * and/or rt should raise errors.
1829 fn test_dedup_shared() {
1830 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1832 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1834 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1837 * If the pointers were leaked or otherwise misused, valgrind and/or
1838 * rt should raise errors.
1844 let mut v = vec![1u, 2, 3, 4, 5];
1846 assert_eq!(v, vec![1u, 3, 5]);
1850 fn test_element_swaps() {
1851 let mut v = [1i, 2, 3];
1852 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1855 0 => assert!(v == [1, 3, 2]),
1856 1 => assert!(v == [3, 1, 2]),
1857 2 => assert!(v == [3, 2, 1]),
1858 3 => assert!(v == [2, 3, 1]),
1859 4 => assert!(v == [2, 1, 3]),
1860 5 => assert!(v == [1, 2, 3]),
1867 fn test_permutations() {
1869 let v: [int; 0] = [];
1870 let mut it = v.permutations();
1871 let (min_size, max_opt) = it.size_hint();
1872 assert_eq!(min_size, 1);
1873 assert_eq!(max_opt.unwrap(), 1);
1874 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1875 assert_eq!(it.next(), None);
1878 let v = ["Hello".to_string()];
1879 let mut it = v.permutations();
1880 let (min_size, max_opt) = it.size_hint();
1881 assert_eq!(min_size, 1);
1882 assert_eq!(max_opt.unwrap(), 1);
1883 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1884 assert_eq!(it.next(), None);
1888 let mut it = v.permutations();
1889 let (min_size, max_opt) = it.size_hint();
1890 assert_eq!(min_size, 3*2);
1891 assert_eq!(max_opt.unwrap(), 3*2);
1892 assert_eq!(it.next(), Some(vec![1,2,3]));
1893 assert_eq!(it.next(), Some(vec![1,3,2]));
1894 assert_eq!(it.next(), Some(vec![3,1,2]));
1895 let (min_size, max_opt) = it.size_hint();
1896 assert_eq!(min_size, 3);
1897 assert_eq!(max_opt.unwrap(), 3);
1898 assert_eq!(it.next(), Some(vec![3,2,1]));
1899 assert_eq!(it.next(), Some(vec![2,3,1]));
1900 assert_eq!(it.next(), Some(vec![2,1,3]));
1901 assert_eq!(it.next(), None);
1904 // check that we have N! permutations
1905 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1907 let mut it = v.permutations();
1908 let (min_size, max_opt) = it.size_hint();
1912 assert_eq!(amt, it.swaps.swaps_made);
1913 assert_eq!(amt, min_size);
1914 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1915 assert_eq!(amt, max_opt.unwrap());
1920 fn test_lexicographic_permutations() {
1921 let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1922 assert!(v.prev_permutation() == false);
1923 assert!(v.next_permutation());
1924 let b: &mut[int] = &mut[1, 2, 3, 5, 4];
1926 assert!(v.prev_permutation());
1927 let b: &mut[int] = &mut[1, 2, 3, 4, 5];
1929 assert!(v.next_permutation());
1930 assert!(v.next_permutation());
1931 let b: &mut[int] = &mut[1, 2, 4, 3, 5];
1933 assert!(v.next_permutation());
1934 let b: &mut[int] = &mut[1, 2, 4, 5, 3];
1937 let v : &mut[int] = &mut[1i, 0, 0, 0];
1938 assert!(v.next_permutation() == false);
1939 assert!(v.prev_permutation());
1940 let b: &mut[int] = &mut[0, 1, 0, 0];
1942 assert!(v.prev_permutation());
1943 let b: &mut[int] = &mut[0, 0, 1, 0];
1945 assert!(v.prev_permutation());
1946 let b: &mut[int] = &mut[0, 0, 0, 1];
1948 assert!(v.prev_permutation() == false);
1952 fn test_lexicographic_permutations_empty_and_short() {
1953 let empty : &mut[int] = &mut[];
1954 assert!(empty.next_permutation() == false);
1955 let b: &mut[int] = &mut[];
1956 assert!(empty == b);
1957 assert!(empty.prev_permutation() == false);
1958 assert!(empty == b);
1960 let one_elem : &mut[int] = &mut[4i];
1961 assert!(one_elem.prev_permutation() == false);
1962 let b: &mut[int] = &mut[4];
1963 assert!(one_elem == b);
1964 assert!(one_elem.next_permutation() == false);
1965 assert!(one_elem == b);
1967 let two_elem : &mut[int] = &mut[1i, 2];
1968 assert!(two_elem.prev_permutation() == false);
1969 let b : &mut[int] = &mut[1, 2];
1970 let c : &mut[int] = &mut[2, 1];
1971 assert!(two_elem == b);
1972 assert!(two_elem.next_permutation());
1973 assert!(two_elem == c);
1974 assert!(two_elem.next_permutation() == false);
1975 assert!(two_elem == c);
1976 assert!(two_elem.prev_permutation());
1977 assert!(two_elem == b);
1978 assert!(two_elem.prev_permutation() == false);
1979 assert!(two_elem == b);
1983 fn test_position_elem() {
1984 assert!([].position_elem(&1i).is_none());
1986 let v1 = vec![1i, 2, 3, 3, 2, 5];
1987 assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
1988 assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
1989 assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
1990 assert!(v1.as_slice().position_elem(&4).is_none());
1994 fn test_binary_search() {
1995 assert_eq!([1i,2,3,4,5].binary_search(&5).ok(), Some(4));
1996 assert_eq!([1i,2,3,4,5].binary_search(&4).ok(), Some(3));
1997 assert_eq!([1i,2,3,4,5].binary_search(&3).ok(), Some(2));
1998 assert_eq!([1i,2,3,4,5].binary_search(&2).ok(), Some(1));
1999 assert_eq!([1i,2,3,4,5].binary_search(&1).ok(), Some(0));
2001 assert_eq!([2i,4,6,8,10].binary_search(&1).ok(), None);
2002 assert_eq!([2i,4,6,8,10].binary_search(&5).ok(), None);
2003 assert_eq!([2i,4,6,8,10].binary_search(&4).ok(), Some(1));
2004 assert_eq!([2i,4,6,8,10].binary_search(&10).ok(), Some(4));
2006 assert_eq!([2i,4,6,8].binary_search(&1).ok(), None);
2007 assert_eq!([2i,4,6,8].binary_search(&5).ok(), None);
2008 assert_eq!([2i,4,6,8].binary_search(&4).ok(), Some(1));
2009 assert_eq!([2i,4,6,8].binary_search(&8).ok(), Some(3));
2011 assert_eq!([2i,4,6].binary_search(&1).ok(), None);
2012 assert_eq!([2i,4,6].binary_search(&5).ok(), None);
2013 assert_eq!([2i,4,6].binary_search(&4).ok(), Some(1));
2014 assert_eq!([2i,4,6].binary_search(&6).ok(), Some(2));
2016 assert_eq!([2i,4].binary_search(&1).ok(), None);
2017 assert_eq!([2i,4].binary_search(&5).ok(), None);
2018 assert_eq!([2i,4].binary_search(&2).ok(), Some(0));
2019 assert_eq!([2i,4].binary_search(&4).ok(), Some(1));
2021 assert_eq!([2i].binary_search(&1).ok(), None);
2022 assert_eq!([2i].binary_search(&5).ok(), None);
2023 assert_eq!([2i].binary_search(&2).ok(), Some(0));
2025 assert_eq!([].binary_search(&1i).ok(), None);
2026 assert_eq!([].binary_search(&5i).ok(), None);
2028 assert!([1i,1,1,1,1].binary_search(&1).ok() != None);
2029 assert!([1i,1,1,1,2].binary_search(&1).ok() != None);
2030 assert!([1i,1,1,2,2].binary_search(&1).ok() != None);
2031 assert!([1i,1,2,2,2].binary_search(&1).ok() != None);
2032 assert_eq!([1i,2,2,2,2].binary_search(&1).ok(), Some(0));
2034 assert_eq!([1i,2,3,4,5].binary_search(&6).ok(), None);
2035 assert_eq!([1i,2,3,4,5].binary_search(&0).ok(), None);
2040 let mut v: Vec<int> = vec![10i, 20];
2041 assert_eq!(v[0], 10);
2042 assert_eq!(v[1], 20);
2044 assert_eq!(v[0], 20);
2045 assert_eq!(v[1], 10);
2047 let mut v3: Vec<int> = vec![];
2049 assert!(v3.is_empty());
2054 for len in range(4u, 25) {
2055 for _ in range(0i, 100) {
2056 let mut v = thread_rng().gen_iter::<uint>().take(len)
2057 .collect::<Vec<uint>>();
2058 let mut v1 = v.clone();
2061 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
2063 v1.sort_by(|a, b| a.cmp(b));
2064 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
2066 v1.sort_by(|a, b| b.cmp(a));
2067 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
2072 let mut v: [uint; 0] = [];
2075 let mut v = [0xDEADBEEFu];
2077 assert!(v == [0xDEADBEEF]);
2081 fn test_sort_stability() {
2082 for len in range(4i, 25) {
2083 for _ in range(0u, 10) {
2084 let mut counts = [0i; 10];
2086 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
2087 // where the first item of each tuple is random, but
2088 // the second item represents which occurrence of that
2089 // number this element is, i.e. the second elements
2090 // will occur in sorted order.
2091 let mut v = range(0, len).map(|_| {
2092 let n = thread_rng().gen::<uint>() % 10;
2095 }).collect::<Vec<(uint, int)>>();
2097 // only sort on the first element, so an unstable sort
2098 // may mix up the counts.
2099 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
2101 // this comparison includes the count (the second item
2102 // of the tuple), so elements with equal first items
2103 // will need to be ordered with increasing
2104 // counts... i.e. exactly asserting that this sort is
2106 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
2112 fn test_partition() {
2113 assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
2114 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2115 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2116 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2120 fn test_partitioned() {
2121 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
2122 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2123 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2124 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2129 let v: [Vec<int>; 0] = [];
2130 let c: Vec<int> = v.concat();
2132 let d: Vec<int> = [vec![1i], vec![2i,3i]].concat();
2133 assert_eq!(d, vec![1i, 2, 3]);
2135 let v: [&[int]; 2] = [&[1], &[2, 3]];
2136 assert_eq!(v.connect(&0), vec![1i, 0, 2, 3]);
2137 let v: [&[int]; 3] = [&[1i], &[2], &[3]];
2138 assert_eq!(v.connect(&0), vec![1i, 0, 2, 0, 3]);
2143 let v: [Vec<int>; 0] = [];
2144 assert_eq!(v.connect_vec(&0), vec![]);
2145 assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
2146 assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
2148 let v: [&[int]; 2] = [&[1], &[2, 3]];
2149 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
2150 let v: [&[int]; 3] = [&[1], &[2], &[3]];
2151 assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
2156 let mut a = vec![1i, 2, 4];
2158 assert_eq!(a, vec![1, 2, 3, 4]);
2160 let mut a = vec![1i, 2, 3];
2162 assert_eq!(a, vec![0, 1, 2, 3]);
2164 let mut a = vec![1i, 2, 3];
2166 assert_eq!(a, vec![1, 2, 3, 4]);
2170 assert_eq!(a, vec![1]);
2175 fn test_insert_oob() {
2176 let mut a = vec![1i, 2, 3];
2182 let mut a = vec![1i,2,3,4];
2184 assert_eq!(a.remove(2), 3);
2185 assert_eq!(a, vec![1i,2,4]);
2187 assert_eq!(a.remove(2), 4);
2188 assert_eq!(a, vec![1i,2]);
2190 assert_eq!(a.remove(0), 1);
2191 assert_eq!(a, vec![2i]);
2193 assert_eq!(a.remove(0), 2);
2194 assert_eq!(a, vec![]);
2199 fn test_remove_fail() {
2200 let mut a = vec![1i];
2201 let _ = a.remove(0);
2202 let _ = a.remove(0);
2206 fn test_capacity() {
2207 let mut v = vec![0u64];
2208 v.reserve_exact(10u);
2209 assert!(v.capacity() >= 11u);
2210 let mut v = vec![0u32];
2211 v.reserve_exact(10u);
2212 assert!(v.capacity() >= 11u);
2217 let v = vec![1i, 2, 3, 4, 5];
2218 let v = v.slice(1u, 3u);
2219 assert_eq!(v.len(), 2u);
2220 assert_eq!(v[0], 2);
2221 assert_eq!(v[1], 3);
2227 fn test_from_fn_fail() {
2228 Vec::from_fn(100, |v| {
2229 if v == 50 { panic!() }
2236 fn test_from_elem_fail() {
2240 boxes: (Box<int>, Rc<int>)
2244 fn clone(&self) -> S {
2245 self.f.set(self.f.get() + 1);
2246 if self.f.get() == 10 { panic!() }
2249 boxes: self.boxes.clone(),
2256 boxes: (box 0, Rc::new(0)),
2258 let _ = Vec::from_elem(100, s);
2263 fn test_grow_fn_fail() {
2265 v.grow_fn(100, |i| {
2269 (box 0i, Rc::new(0i))
2275 fn test_permute_fail() {
2276 let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
2277 (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
2279 for _ in v.permutations() {
2288 fn test_total_ord() {
2289 let c: &[int] = &[1, 2, 3];
2290 [1, 2, 3, 4][].cmp(c) == Greater;
2291 let c: &[int] = &[1, 2, 3, 4];
2292 [1, 2, 3][].cmp(c) == Less;
2293 let c: &[int] = &[1, 2, 3, 6];
2294 [1, 2, 3, 4][].cmp(c) == Equal;
2295 let c: &[int] = &[1, 2, 3, 4, 5, 6];
2296 [1, 2, 3, 4, 5, 5, 5, 5][].cmp(c) == Less;
2297 let c: &[int] = &[1, 2, 3, 4];
2298 [2, 2][].cmp(c) == Greater;
2302 fn test_iterator() {
2303 let xs = [1i, 2, 5, 10, 11];
2304 let mut it = xs.iter();
2305 assert_eq!(it.size_hint(), (5, Some(5)));
2306 assert_eq!(it.next().unwrap(), &1);
2307 assert_eq!(it.size_hint(), (4, Some(4)));
2308 assert_eq!(it.next().unwrap(), &2);
2309 assert_eq!(it.size_hint(), (3, Some(3)));
2310 assert_eq!(it.next().unwrap(), &5);
2311 assert_eq!(it.size_hint(), (2, Some(2)));
2312 assert_eq!(it.next().unwrap(), &10);
2313 assert_eq!(it.size_hint(), (1, Some(1)));
2314 assert_eq!(it.next().unwrap(), &11);
2315 assert_eq!(it.size_hint(), (0, Some(0)));
2316 assert!(it.next().is_none());
2320 fn test_random_access_iterator() {
2321 let xs = [1i, 2, 5, 10, 11];
2322 let mut it = xs.iter();
2324 assert_eq!(it.indexable(), 5);
2325 assert_eq!(it.idx(0).unwrap(), &1);
2326 assert_eq!(it.idx(2).unwrap(), &5);
2327 assert_eq!(it.idx(4).unwrap(), &11);
2328 assert!(it.idx(5).is_none());
2330 assert_eq!(it.next().unwrap(), &1);
2331 assert_eq!(it.indexable(), 4);
2332 assert_eq!(it.idx(0).unwrap(), &2);
2333 assert_eq!(it.idx(3).unwrap(), &11);
2334 assert!(it.idx(4).is_none());
2336 assert_eq!(it.next().unwrap(), &2);
2337 assert_eq!(it.indexable(), 3);
2338 assert_eq!(it.idx(1).unwrap(), &10);
2339 assert!(it.idx(3).is_none());
2341 assert_eq!(it.next().unwrap(), &5);
2342 assert_eq!(it.indexable(), 2);
2343 assert_eq!(it.idx(1).unwrap(), &11);
2345 assert_eq!(it.next().unwrap(), &10);
2346 assert_eq!(it.indexable(), 1);
2347 assert_eq!(it.idx(0).unwrap(), &11);
2348 assert!(it.idx(1).is_none());
2350 assert_eq!(it.next().unwrap(), &11);
2351 assert_eq!(it.indexable(), 0);
2352 assert!(it.idx(0).is_none());
2354 assert!(it.next().is_none());
2358 fn test_iter_size_hints() {
2359 let mut xs = [1i, 2, 5, 10, 11];
2360 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
2361 assert_eq!(xs.iter_mut().size_hint(), (5, Some(5)));
2365 fn test_iter_clone() {
2366 let xs = [1i, 2, 5];
2367 let mut it = xs.iter();
2369 let mut jt = it.clone();
2370 assert_eq!(it.next(), jt.next());
2371 assert_eq!(it.next(), jt.next());
2372 assert_eq!(it.next(), jt.next());
2376 fn test_mut_iterator() {
2377 let mut xs = [1i, 2, 3, 4, 5];
2378 for x in xs.iter_mut() {
2381 assert!(xs == [2, 3, 4, 5, 6])
2385 fn test_rev_iterator() {
2387 let xs = [1i, 2, 5, 10, 11];
2388 let ys = [11, 10, 5, 2, 1];
2390 for &x in xs.iter().rev() {
2391 assert_eq!(x, ys[i]);
2398 fn test_mut_rev_iterator() {
2399 let mut xs = [1u, 2, 3, 4, 5];
2400 for (i,x) in xs.iter_mut().rev().enumerate() {
2403 assert!(xs == [5, 5, 5, 5, 5])
2407 fn test_move_iterator() {
2408 let xs = vec![1u,2,3,4,5];
2409 assert_eq!(xs.into_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
2413 fn test_move_rev_iterator() {
2414 let xs = vec![1u,2,3,4,5];
2415 assert_eq!(xs.into_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
2419 fn test_splitator() {
2420 let xs = &[1i,2,3,4,5];
2422 let splits: &[&[int]] = &[&[1], &[3], &[5]];
2423 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2425 let splits: &[&[int]] = &[&[], &[2,3,4,5]];
2426 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>(),
2428 let splits: &[&[int]] = &[&[1,2,3,4], &[]];
2429 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(),
2431 let splits: &[&[int]] = &[&[1,2,3,4,5]];
2432 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>(),
2434 let splits: &[&[int]] = &[&[], &[], &[], &[], &[], &[]];
2435 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>(),
2438 let xs: &[int] = &[];
2439 let splits: &[&[int]] = &[&[]];
2440 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(), splits);
2444 fn test_splitnator() {
2445 let xs = &[1i,2,3,4,5];
2447 let splits: &[&[int]] = &[&[1,2,3,4,5]];
2448 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2450 let splits: &[&[int]] = &[&[1], &[3,4,5]];
2451 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2453 let splits: &[&[int]] = &[&[], &[], &[], &[4,5]];
2454 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>(),
2457 let xs: &[int] = &[];
2458 let splits: &[&[int]] = &[&[]];
2459 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
2463 fn test_splitnator_mut() {
2464 let xs = &mut [1i,2,3,4,5];
2466 let splits: &[&mut [int]] = &[&mut [1,2,3,4,5]];
2467 assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
2469 let splits: &[&mut [int]] = &[&mut [1], &mut [3,4,5]];
2470 assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
2472 let splits: &[&mut [int]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
2473 assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<&mut [int]>>(),
2476 let xs: &mut [int] = &mut [];
2477 let splits: &[&mut [int]] = &[&mut []];
2478 assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<&mut [int]>>(),
2483 fn test_rsplitator() {
2484 let xs = &[1i,2,3,4,5];
2486 let splits: &[&[int]] = &[&[5], &[3], &[1]];
2487 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>(),
2489 let splits: &[&[int]] = &[&[2,3,4,5], &[]];
2490 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>(),
2492 let splits: &[&[int]] = &[&[], &[1,2,3,4]];
2493 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(),
2495 let splits: &[&[int]] = &[&[1,2,3,4,5]];
2496 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>(),
2499 let xs: &[int] = &[];
2500 let splits: &[&[int]] = &[&[]];
2501 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(), splits);
2505 fn test_rsplitnator() {
2506 let xs = &[1,2,3,4,5];
2508 let splits: &[&[int]] = &[&[1,2,3,4,5]];
2509 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2511 let splits: &[&[int]] = &[&[5], &[1,2,3]];
2512 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2514 let splits: &[&[int]] = &[&[], &[], &[], &[1,2]];
2515 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>(),
2518 let xs: &[int] = &[];
2519 let splits: &[&[int]] = &[&[]];
2520 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
2524 fn test_windowsator() {
2525 let v = &[1i,2,3,4];
2527 let wins: &[&[int]] = &[&[1,2], &[2,3], &[3,4]];
2528 assert_eq!(v.windows(2).collect::<Vec<&[int]>>(), wins);
2529 let wins: &[&[int]] = &[&[1i,2,3], &[2,3,4]];
2530 assert_eq!(v.windows(3).collect::<Vec<&[int]>>(), wins);
2531 assert!(v.windows(6).next().is_none());
2536 fn test_windowsator_0() {
2537 let v = &[1i,2,3,4];
2538 let _it = v.windows(0);
2542 fn test_chunksator() {
2543 let v = &[1i,2,3,4,5];
2545 let chunks: &[&[int]] = &[&[1i,2], &[3,4], &[5]];
2546 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>(), chunks);
2547 let chunks: &[&[int]] = &[&[1i,2,3], &[4,5]];
2548 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>(), chunks);
2549 let chunks: &[&[int]] = &[&[1i,2,3,4,5]];
2550 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>(), chunks);
2552 let chunks: &[&[int]] = &[&[5i], &[3,4], &[1,2]];
2553 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>(), chunks);
2554 let mut it = v.chunks(2);
2555 assert_eq!(it.indexable(), 3);
2556 let chunk: &[int] = &[1,2];
2557 assert_eq!(it.idx(0).unwrap(), chunk);
2558 let chunk: &[int] = &[3,4];
2559 assert_eq!(it.idx(1).unwrap(), chunk);
2560 let chunk: &[int] = &[5];
2561 assert_eq!(it.idx(2).unwrap(), chunk);
2562 assert_eq!(it.idx(3), None);
2567 fn test_chunksator_0() {
2568 let v = &[1i,2,3,4];
2569 let _it = v.chunks(0);
2573 fn test_move_from() {
2574 let mut a = [1i,2,3,4,5];
2575 let b = vec![6i,7,8];
2576 assert_eq!(a.move_from(b, 0, 3), 3);
2577 assert!(a == [6i,7,8,4,5]);
2578 let mut a = [7i,2,8,1];
2579 let b = vec![3i,1,4,1,5,9];
2580 assert_eq!(a.move_from(b, 0, 6), 4);
2581 assert!(a == [3i,1,4,1]);
2582 let mut a = [1i,2,3,4];
2583 let b = vec![5i,6,7,8,9,0];
2584 assert_eq!(a.move_from(b, 2, 3), 1);
2585 assert!(a == [7i,2,3,4]);
2586 let mut a = [1i,2,3,4,5];
2587 let b = vec![5i,6,7,8,9,0];
2588 assert_eq!(a.slice_mut(2, 4).move_from(b,1,6), 2);
2589 assert!(a == [1i,2,6,7,5]);
2593 fn test_reverse_part() {
2594 let mut values = [1i,2,3,4,5];
2595 values.slice_mut(1, 4).reverse();
2596 assert!(values == [1,4,3,2,5]);
2601 macro_rules! test_show_vec {
2602 ($x:expr, $x_str:expr) => ({
2603 let (x, x_str) = ($x, $x_str);
2604 assert_eq!(format!("{}", x), x_str);
2605 assert_eq!(format!("{}", x.as_slice()), x_str);
2608 let empty: Vec<int> = vec![];
2609 test_show_vec!(empty, "[]");
2610 test_show_vec!(vec![1i], "[1]");
2611 test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]");
2612 test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
2613 "[[], [1], [1, 1]]");
2615 let empty_mut: &mut [int] = &mut[];
2616 test_show_vec!(empty_mut, "[]");
2617 let v: &mut[int] = &mut[1];
2618 test_show_vec!(v, "[1]");
2619 let v: &mut[int] = &mut[1, 2, 3];
2620 test_show_vec!(v, "[1, 2, 3]");
2621 let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]];
2622 test_show_vec!(v, "[[], [1], [1, 1]]");
2626 fn test_vec_default() {
2629 let v: $ty = Default::default();
2630 assert!(v.is_empty());
2639 fn test_bytes_set_memory() {
2640 use slice::bytes::MutableByteVector;
2641 let mut values = [1u8,2,3,4,5];
2642 values.slice_mut(0, 5).set_memory(0xAB);
2643 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
2644 values.slice_mut(2, 4).set_memory(0xFF);
2645 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
2650 fn test_overflow_does_not_cause_segfault() {
2652 v.reserve_exact(-1);
2659 fn test_overflow_does_not_cause_segfault_managed() {
2660 let mut v = vec![Rc::new(1i)];
2661 v.reserve_exact(-1);
2662 v.push(Rc::new(2i));
2666 fn test_mut_split_at() {
2667 let mut values = [1u8,2,3,4,5];
2669 let (left, right) = values.split_at_mut(2);
2671 let left: &[_] = left;
2672 assert!(left[0..left.len()] == [1, 2][]);
2674 for p in left.iter_mut() {
2679 let right: &[_] = right;
2680 assert!(right[0..right.len()] == [3, 4, 5][]);
2682 for p in right.iter_mut() {
2687 assert!(values == [2, 3, 5, 6, 7]);
2690 #[deriving(Clone, PartialEq)]
2694 fn test_iter_zero_sized() {
2695 let mut v = vec![Foo, Foo, Foo];
2696 assert_eq!(v.len(), 3);
2705 for f in v[1..3].iter() {
2711 for f in v.iter_mut() {
2717 for f in v.into_iter() {
2721 assert_eq!(cnt, 11);
2723 let xs: [Foo; 3] = [Foo, Foo, Foo];
2725 for f in xs.iter() {
2733 fn test_shrink_to_fit() {
2734 let mut xs = vec![0, 1, 2, 3];
2735 for i in range(4i, 100) {
2738 assert_eq!(xs.capacity(), 128);
2740 assert_eq!(xs.capacity(), 100);
2741 assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
2745 fn test_starts_with() {
2746 assert!(b"foobar".starts_with(b"foo"));
2747 assert!(!b"foobar".starts_with(b"oob"));
2748 assert!(!b"foobar".starts_with(b"bar"));
2749 assert!(!b"foo".starts_with(b"foobar"));
2750 assert!(!b"bar".starts_with(b"foobar"));
2751 assert!(b"foobar".starts_with(b"foobar"));
2752 let empty: &[u8] = &[];
2753 assert!(empty.starts_with(empty));
2754 assert!(!empty.starts_with(b"foo"));
2755 assert!(b"foobar".starts_with(empty));
2759 fn test_ends_with() {
2760 assert!(b"foobar".ends_with(b"bar"));
2761 assert!(!b"foobar".ends_with(b"oba"));
2762 assert!(!b"foobar".ends_with(b"foo"));
2763 assert!(!b"foo".ends_with(b"foobar"));
2764 assert!(!b"bar".ends_with(b"foobar"));
2765 assert!(b"foobar".ends_with(b"foobar"));
2766 let empty: &[u8] = &[];
2767 assert!(empty.ends_with(empty));
2768 assert!(!empty.ends_with(b"foo"));
2769 assert!(b"foobar".ends_with(empty));
2773 fn test_mut_splitator() {
2774 let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2775 assert_eq!(xs.split_mut(|x| *x == 0).count(), 6);
2776 for slice in xs.split_mut(|x| *x == 0) {
2779 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2781 let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2782 for slice in xs.split_mut(|x| *x == 0).take(5) {
2785 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2789 fn test_mut_splitator_rev() {
2790 let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2791 for slice in xs.split_mut(|x| *x == 0).rev().take(4) {
2794 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2799 let mut v = [0i,1,2];
2800 assert_eq!(v.get_mut(3), None);
2801 v.get_mut(1).map(|e| *e = 7);
2802 assert_eq!(v[1], 7);
2804 assert_eq!(v.get_mut(2), Some(&mut x));
2808 fn test_mut_chunks() {
2809 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2810 for (i, chunk) in v.chunks_mut(3).enumerate() {
2811 for x in chunk.iter_mut() {
2815 let result = [0u8, 0, 0, 1, 1, 1, 2];
2816 assert!(v == result);
2820 fn test_mut_chunks_rev() {
2821 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2822 for (i, chunk) in v.chunks_mut(3).rev().enumerate() {
2823 for x in chunk.iter_mut() {
2827 let result = [2u8, 2, 2, 1, 1, 1, 0];
2828 assert!(v == result);
2833 fn test_mut_chunks_0() {
2834 let mut v = [1i, 2, 3, 4];
2835 let _it = v.chunks_mut(0);
2839 fn test_mut_last() {
2840 let mut x = [1i, 2, 3, 4, 5];
2841 let h = x.last_mut();
2842 assert_eq!(*h.unwrap(), 5);
2844 let y: &mut [int] = &mut [];
2845 assert!(y.last_mut().is_none());
2850 let xs = box [1u, 2, 3];
2851 let ys = xs.to_vec();
2852 assert_eq!(ys, [1u, 2, 3]);
2861 use std::rand::{weak_rng, Rng};
2862 use test::{Bencher, black_box};
2865 fn iterator(b: &mut Bencher) {
2866 // peculiar numbers to stop LLVM from optimising the summation
2868 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2875 // sum == 11806, to stop dead code elimination.
2876 if sum == 0 {panic!()}
2881 fn mut_iterator(b: &mut Bencher) {
2882 let mut v = Vec::from_elem(100, 0i);
2886 for x in v.iter_mut() {
2894 fn concat(b: &mut Bencher) {
2895 let xss: Vec<Vec<uint>> =
2896 Vec::from_fn(100, |i| range(0u, i).collect());
2898 xss.as_slice().concat();
2903 fn connect(b: &mut Bencher) {
2904 let xss: Vec<Vec<uint>> =
2905 Vec::from_fn(100, |i| range(0u, i).collect());
2907 xss.as_slice().connect_vec(&0)
2912 fn push(b: &mut Bencher) {
2913 let mut vec: Vec<uint> = vec![];
2921 fn starts_with_same_vector(b: &mut Bencher) {
2922 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2924 vec.as_slice().starts_with(vec.as_slice())
2929 fn starts_with_single_element(b: &mut Bencher) {
2930 let vec: Vec<uint> = vec![0];
2932 vec.as_slice().starts_with(vec.as_slice())
2937 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2938 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2939 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2942 vec.as_slice().starts_with(match_vec.as_slice())
2947 fn ends_with_same_vector(b: &mut Bencher) {
2948 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2950 vec.as_slice().ends_with(vec.as_slice())
2955 fn ends_with_single_element(b: &mut Bencher) {
2956 let vec: Vec<uint> = vec![0];
2958 vec.as_slice().ends_with(vec.as_slice())
2963 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2964 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2965 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2966 match_vec.as_mut_slice()[0] = 200;
2968 vec.as_slice().starts_with(match_vec.as_slice())
2973 fn contains_last_element(b: &mut Bencher) {
2974 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2981 fn zero_1kb_from_elem(b: &mut Bencher) {
2983 Vec::from_elem(1024, 0u8)
2988 fn zero_1kb_set_memory(b: &mut Bencher) {
2990 let mut v: Vec<uint> = Vec::with_capacity(1024);
2992 let vp = v.as_mut_ptr();
2993 ptr::set_memory(vp, 0, 1024);
3001 fn zero_1kb_loop_set(b: &mut Bencher) {
3003 let mut v: Vec<uint> = Vec::with_capacity(1024);
3007 for i in range(0u, 1024) {
3014 fn zero_1kb_mut_iter(b: &mut Bencher) {
3016 let mut v = Vec::with_capacity(1024);
3020 for x in v.iter_mut() {
3028 fn random_inserts(b: &mut Bencher) {
3029 let mut rng = weak_rng();
3031 let mut v = Vec::from_elem(30, (0u, 0u));
3032 for _ in range(0u, 100) {
3034 v.insert(rng.gen::<uint>() % (l + 1),
3040 fn random_removes(b: &mut Bencher) {
3041 let mut rng = weak_rng();
3043 let mut v = Vec::from_elem(130, (0u, 0u));
3044 for _ in range(0u, 100) {
3046 v.remove(rng.gen::<uint>() % l);
3052 fn sort_random_small(b: &mut Bencher) {
3053 let mut rng = weak_rng();
3055 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
3056 v.as_mut_slice().sort();
3058 b.bytes = 5 * mem::size_of::<u64>() as u64;
3062 fn sort_random_medium(b: &mut Bencher) {
3063 let mut rng = weak_rng();
3065 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
3066 v.as_mut_slice().sort();
3068 b.bytes = 100 * mem::size_of::<u64>() as u64;
3072 fn sort_random_large(b: &mut Bencher) {
3073 let mut rng = weak_rng();
3075 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
3076 v.as_mut_slice().sort();
3078 b.bytes = 10000 * mem::size_of::<u64>() as u64;
3082 fn sort_sorted(b: &mut Bencher) {
3083 let mut v = Vec::from_fn(10000, |i| i);
3087 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3090 type BigSortable = (u64,u64,u64,u64);
3093 fn sort_big_random_small(b: &mut Bencher) {
3094 let mut rng = weak_rng();
3096 let mut v = rng.gen_iter::<BigSortable>().take(5)
3097 .collect::<Vec<BigSortable>>();
3100 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
3104 fn sort_big_random_medium(b: &mut Bencher) {
3105 let mut rng = weak_rng();
3107 let mut v = rng.gen_iter::<BigSortable>().take(100)
3108 .collect::<Vec<BigSortable>>();
3111 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
3115 fn sort_big_random_large(b: &mut Bencher) {
3116 let mut rng = weak_rng();
3118 let mut v = rng.gen_iter::<BigSortable>().take(10000)
3119 .collect::<Vec<BigSortable>>();
3122 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
3126 fn sort_big_sorted(b: &mut Bencher) {
3127 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
3131 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;