1 // Copyright 2012-2015 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[i32] = &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)`:
56 //! let numbers = [0, 1, 2];
57 //! let last_numbers = &numbers[1..3];
58 //! // last_numbers is now &[1, 2]
62 //! ## Implementations of other traits
64 //! There are several implementations of common traits for slices. Some examples
68 //! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
69 //! * `Hash` - for slices whose element type is `Hash`
73 //! The method `iter()` returns an iteration value for a slice. The iterator
74 //! yields references to the slice's elements, so if the element
75 //! type of the slice is `isize`, the element type of the iterator is `&isize`.
78 //! let numbers = [0, 1, 2];
79 //! for &x in numbers.iter() {
80 //! println!("{} is a number!", x);
84 //! * `.iter_mut()` returns an iterator that allows modifying each value.
85 //! * Further iterators exist that split, chunk or permute the slice.
87 #![doc(primitive = "slice")]
88 #![stable(feature = "rust1", since = "1.0.0")]
90 use alloc::boxed::Box;
91 use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned};
92 use core::clone::Clone;
93 use core::cmp::Ordering::{self, Greater, Less};
94 use core::cmp::{self, Ord, PartialEq};
95 use core::iter::{Iterator, IteratorExt};
96 use core::iter::{range_step, MultiplicativeIterator};
97 use core::marker::Sized;
98 use core::mem::size_of;
100 use core::ops::FnMut;
101 use core::option::Option::{self, Some, None};
102 use core::ptr::PtrExt;
104 use core::result::Result;
105 use core::slice as core_slice;
106 use self::Direction::*;
110 pub use core::slice::{Chunks, AsSlice, Windows};
111 pub use core::slice::{Iter, IterMut};
112 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
113 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
114 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
115 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
116 pub use core::slice::{from_raw_buf, from_raw_mut_buf};
118 ////////////////////////////////////////////////////////////////////////////////
119 // Basic slice extension methods
120 ////////////////////////////////////////////////////////////////////////////////
122 /// Allocating extension methods for slices.
123 #[stable(feature = "rust1", since = "1.0.0")]
125 #[stable(feature = "rust1", since = "1.0.0")]
128 /// Sorts the slice, in place, using `compare` to compare
131 /// This sort is `O(n log n)` worst-case and stable, but allocates
132 /// approximately `2 * n`, where `n` is the length of `self`.
137 /// let mut v = [5, 4, 1, 3, 2];
138 /// v.sort_by(|a, b| a.cmp(b));
139 /// assert!(v == [1, 2, 3, 4, 5]);
141 /// // reverse sorting
142 /// v.sort_by(|a, b| b.cmp(a));
143 /// assert!(v == [5, 4, 3, 2, 1]);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 fn sort_by<F>(&mut self, compare: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
148 /// Consumes `src` and moves as many elements as it can into `self`
149 /// from the range [start,end).
151 /// Returns the number of elements copied (the shorter of `self.len()`
152 /// and `end - start`).
156 /// * src - A mutable vector of `T`
157 /// * start - The index into `src` to start copying from
158 /// * end - The index into `src` to stop copying from
163 /// let mut a = [1, 2, 3, 4, 5];
164 /// let b = vec![6, 7, 8];
165 /// let num_moved = a.move_from(b, 0, 3);
166 /// assert_eq!(num_moved, 3);
167 /// assert!(a == [6, 7, 8, 4, 5]);
169 #[unstable(feature = "collections",
170 reason = "uncertain about this API approach")]
171 fn move_from(&mut self, src: Vec<Self::Item>, start: usize, end: usize) -> usize;
173 /// Deprecated: use `&s[start .. end]` notation instead.
174 #[unstable(feature = "collections",
175 reason = "will be replaced by slice syntax")]
176 #[deprecated(since = "1.0.0", reason = "use &s[start .. end] instead")]
177 fn slice(&self, start: usize, end: usize) -> &[Self::Item];
179 /// Deprecated: use `&s[start..]` notation instead.
180 #[unstable(feature = "collections",
181 reason = "will be replaced by slice syntax")]
182 #[deprecated(since = "1.0.0", reason = "use &s[start..] instead")]
183 fn slice_from(&self, start: usize) -> &[Self::Item];
185 /// Deprecated: use `&s[..end]` notation instead.
186 #[unstable(feature = "collections",
187 reason = "will be replaced by slice syntax")]
188 #[deprecated(since = "1.0.0", reason = "use &s[..end] instead")]
189 fn slice_to(&self, end: usize) -> &[Self::Item];
191 /// Divides one slice into two at an index.
193 /// The first will contain all indices from `[0, mid)` (excluding
194 /// the index `mid` itself) and the second will contain all
195 /// indices from `[mid, len)` (excluding the index `len` itself).
197 /// Panics if `mid > len`.
202 /// let v = [10, 40, 30, 20, 50];
203 /// let (v1, v2) = v.split_at(2);
204 /// assert_eq!([10, 40], v1);
205 /// assert_eq!([30, 20, 50], v2);
207 #[stable(feature = "rust1", since = "1.0.0")]
208 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
210 /// Returns an iterator over the slice.
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn iter(&self) -> Iter<Self::Item>;
214 /// Returns an iterator over subslices separated by elements that match
215 /// `pred`. The matched element is not contained in the subslices.
219 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
223 /// let v = [10, 40, 30, 20, 60, 50];
224 /// for group in v.split(|num| *num % 3 == 0) {
225 /// println!("{:?}", group);
228 #[stable(feature = "rust1", since = "1.0.0")]
229 fn split<F>(&self, pred: F) -> Split<Self::Item, F>
230 where F: FnMut(&Self::Item) -> bool;
232 /// Returns an iterator over subslices separated by elements that match
233 /// `pred`, limited to splitting at most `n` times. The matched element is
234 /// not contained in the subslices.
238 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
242 /// let v = [10, 40, 30, 20, 60, 50];
243 /// for group in v.splitn(1, |num| *num % 3 == 0) {
244 /// println!("{:?}", group);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 fn splitn<F>(&self, n: usize, pred: F) -> SplitN<Self::Item, F>
249 where F: FnMut(&Self::Item) -> bool;
251 /// Returns an iterator over subslices separated by elements that match
252 /// `pred` limited to splitting at most `n` times. This starts at the end of
253 /// the slice and works backwards. The matched element is not contained in
258 /// Print the slice split once, starting from the end, by numbers divisible
259 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
262 /// let v = [10, 40, 30, 20, 60, 50];
263 /// for group in v.rsplitn(1, |num| *num % 3 == 0) {
264 /// println!("{:?}", group);
267 #[stable(feature = "rust1", since = "1.0.0")]
268 fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<Self::Item, F>
269 where F: FnMut(&Self::Item) -> bool;
271 /// Returns an iterator over all contiguous windows of length
272 /// `size`. The windows overlap. If the slice is shorter than
273 /// `size`, the iterator returns no values.
277 /// Panics if `size` is 0.
281 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
285 /// let v = &[1, 2, 3, 4];
286 /// for win in v.windows(2) {
287 /// println!("{:?}", win);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 fn windows(&self, size: usize) -> Windows<Self::Item>;
293 /// Returns an iterator over `size` elements of the slice at a
294 /// time. The chunks do not overlap. If `size` does not divide the
295 /// length of the slice, then the last chunk will not have length
300 /// Panics if `size` is 0.
304 /// Print the slice two elements at a time (i.e. `[1,2]`,
308 /// let v = &[1, 2, 3, 4, 5];
309 /// for win in v.chunks(2) {
310 /// println!("{:?}", win);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
316 /// Returns the element of a slice at the given index, or `None` if the
317 /// index is out of bounds.
322 /// let v = [10, 40, 30];
323 /// assert_eq!(Some(&40), v.get(1));
324 /// assert_eq!(None, v.get(3));
326 #[stable(feature = "rust1", since = "1.0.0")]
327 fn get(&self, index: usize) -> Option<&Self::Item>;
329 /// Returns the first element of a slice, or `None` if it is empty.
334 /// let v = [10, 40, 30];
335 /// assert_eq!(Some(&10), v.first());
337 /// let w: &[i32] = &[];
338 /// assert_eq!(None, w.first());
340 #[stable(feature = "rust1", since = "1.0.0")]
341 fn first(&self) -> Option<&Self::Item>;
343 /// Returns all but the first element of a slice.
344 #[unstable(feature = "collections", reason = "likely to be renamed")]
345 fn tail(&self) -> &[Self::Item];
347 /// Returns all but the last element of a slice.
348 #[unstable(feature = "collections", reason = "likely to be renamed")]
349 fn init(&self) -> &[Self::Item];
351 /// Returns the last element of a slice, or `None` if it is empty.
356 /// let v = [10, 40, 30];
357 /// assert_eq!(Some(&30), v.last());
359 /// let w: &[i32] = &[];
360 /// assert_eq!(None, w.last());
362 #[stable(feature = "rust1", since = "1.0.0")]
363 fn last(&self) -> Option<&Self::Item>;
365 /// Returns a pointer to the element at the given index, without doing
367 #[stable(feature = "rust1", since = "1.0.0")]
368 unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
370 /// Returns an unsafe pointer to the slice's buffer
372 /// The caller must ensure that the slice outlives the pointer this
373 /// function returns, or else it will end up pointing to garbage.
375 /// Modifying the slice may cause its buffer to be reallocated, which
376 /// would also make any pointers to it invalid.
377 #[stable(feature = "rust1", since = "1.0.0")]
378 fn as_ptr(&self) -> *const Self::Item;
380 /// Binary search a sorted slice with a comparator function.
382 /// The comparator function should implement an order consistent
383 /// with the sort order of the underlying slice, returning an
384 /// order code that indicates whether its argument is `Less`,
385 /// `Equal` or `Greater` the desired target.
387 /// If a matching value is found then returns `Ok`, containing
388 /// the index for the matched element; if no match is found then
389 /// `Err` is returned, containing the index where a matching
390 /// element could be inserted while maintaining sorted order.
394 /// Looks up a series of four elements. The first is found, with a
395 /// uniquely determined position; the second and third are not
396 /// found; the fourth could match any position in `[1,4]`.
399 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
400 /// let s = s.as_slice();
403 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
405 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
407 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
409 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
410 /// assert!(match r { Ok(1...4) => true, _ => false, });
412 #[stable(feature = "rust1", since = "1.0.0")]
413 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
414 F: FnMut(&Self::Item) -> Ordering;
416 /// Return the number of elements in the slice
421 /// let a = [1, 2, 3];
422 /// assert_eq!(a.len(), 3);
424 #[stable(feature = "rust1", since = "1.0.0")]
425 fn len(&self) -> usize;
427 /// Returns true if the slice has a length of 0
432 /// let a = [1, 2, 3];
433 /// assert!(!a.is_empty());
436 #[stable(feature = "rust1", since = "1.0.0")]
437 fn is_empty(&self) -> bool { self.len() == 0 }
438 /// Returns a mutable reference to the element at the given index,
439 /// or `None` if the index is out of bounds
440 #[stable(feature = "rust1", since = "1.0.0")]
441 fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
443 /// Work with `self` as a mut slice.
444 /// Primarily intended for getting a &mut [T] from a [T; N].
445 #[stable(feature = "rust1", since = "1.0.0")]
446 fn as_mut_slice(&mut self) -> &mut [Self::Item];
448 /// Deprecated: use `&mut s[start .. end]` instead.
449 #[unstable(feature = "collections",
450 reason = "will be replaced by slice syntax")]
451 #[deprecated(since = "1.0.0", reason = "use &mut s[start .. end] instead")]
452 fn slice_mut(&mut self, start: usize, end: usize) -> &mut [Self::Item];
454 /// Deprecated: use `&mut s[start ..]` instead.
455 #[unstable(feature = "collections",
456 reason = "will be replaced by slice syntax")]
457 #[deprecated(since = "1.0.0", reason = "use &mut s[start ..] instead")]
458 fn slice_from_mut(&mut self, start: usize) -> &mut [Self::Item];
460 /// Deprecated: use `&mut s[.. end]` instead.
461 #[unstable(feature = "collections",
462 reason = "will be replaced by slice syntax")]
463 #[deprecated(since = "1.0.0", reason = "use &mut s[.. end] instead")]
464 fn slice_to_mut(&mut self, end: usize) -> &mut [Self::Item];
466 /// Returns an iterator that allows modifying each value
467 #[stable(feature = "rust1", since = "1.0.0")]
468 fn iter_mut(&mut self) -> IterMut<Self::Item>;
470 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
471 #[stable(feature = "rust1", since = "1.0.0")]
472 fn first_mut(&mut self) -> Option<&mut Self::Item>;
474 /// Returns all but the first element of a mutable slice
475 #[unstable(feature = "collections",
476 reason = "likely to be renamed or removed")]
477 fn tail_mut(&mut self) -> &mut [Self::Item];
479 /// Returns all but the last element of a mutable slice
480 #[unstable(feature = "collections",
481 reason = "likely to be renamed or removed")]
482 fn init_mut(&mut self) -> &mut [Self::Item];
484 /// Returns a mutable pointer to the last item in the slice.
485 #[stable(feature = "rust1", since = "1.0.0")]
486 fn last_mut(&mut self) -> Option<&mut Self::Item>;
488 /// Returns an iterator over mutable subslices separated by elements that
489 /// match `pred`. The matched element is not contained in the subslices.
490 #[stable(feature = "rust1", since = "1.0.0")]
491 fn split_mut<F>(&mut self, pred: F) -> SplitMut<Self::Item, F>
492 where F: FnMut(&Self::Item) -> bool;
494 /// Returns an iterator over subslices separated by elements that match
495 /// `pred`, limited to splitting at most `n` times. The matched element is
496 /// not contained in the subslices.
497 #[stable(feature = "rust1", since = "1.0.0")]
498 fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<Self::Item, F>
499 where F: FnMut(&Self::Item) -> bool;
501 /// Returns an iterator over subslices separated by elements that match
502 /// `pred` limited to splitting at most `n` times. This starts at the end of
503 /// the slice and works backwards. The matched element is not contained in
505 #[stable(feature = "rust1", since = "1.0.0")]
506 fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<Self::Item, F>
507 where F: FnMut(&Self::Item) -> bool;
509 /// Returns an iterator over `chunk_size` elements of the slice at a time.
510 /// The chunks are mutable and do not overlap. If `chunk_size` does
511 /// not divide the length of the slice, then the last chunk will not
512 /// have length `chunk_size`.
516 /// Panics if `chunk_size` is 0.
517 #[stable(feature = "rust1", since = "1.0.0")]
518 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
520 /// Swaps two elements in a slice.
524 /// * a - The index of the first element
525 /// * b - The index of the second element
529 /// Panics if `a` or `b` are out of bounds.
534 /// let mut v = ["a", "b", "c", "d"];
536 /// assert!(v == ["a", "d", "c", "b"]);
538 #[stable(feature = "rust1", since = "1.0.0")]
539 fn swap(&mut self, a: usize, b: usize);
541 /// Divides one `&mut` into two at an index.
543 /// The first will contain all indices from `[0, mid)` (excluding
544 /// the index `mid` itself) and the second will contain all
545 /// indices from `[mid, len)` (excluding the index `len` itself).
549 /// Panics if `mid > len`.
554 /// let mut v = [1, 2, 3, 4, 5, 6];
556 /// // scoped to restrict the lifetime of the borrows
558 /// let (left, right) = v.split_at_mut(0);
559 /// assert!(left == []);
560 /// assert!(right == [1, 2, 3, 4, 5, 6]);
564 /// let (left, right) = v.split_at_mut(2);
565 /// assert!(left == [1, 2]);
566 /// assert!(right == [3, 4, 5, 6]);
570 /// let (left, right) = v.split_at_mut(6);
571 /// assert!(left == [1, 2, 3, 4, 5, 6]);
572 /// assert!(right == []);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
578 /// Reverse the order of elements in a slice, in place.
583 /// let mut v = [1, 2, 3];
585 /// assert!(v == [3, 2, 1]);
587 #[stable(feature = "rust1", since = "1.0.0")]
588 fn reverse(&mut self);
590 /// Returns an unsafe mutable pointer to the element in index
591 #[stable(feature = "rust1", since = "1.0.0")]
592 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
594 /// Return an unsafe mutable pointer to the slice's buffer.
596 /// The caller must ensure that the slice outlives the pointer this
597 /// function returns, or else it will end up pointing to garbage.
599 /// Modifying the slice may cause its buffer to be reallocated, which
600 /// would also make any pointers to it invalid.
602 #[stable(feature = "rust1", since = "1.0.0")]
603 fn as_mut_ptr(&mut self) -> *mut Self::Item;
605 /// Copies `self` into a new `Vec`.
606 #[stable(feature = "rust1", since = "1.0.0")]
607 fn to_vec(&self) -> Vec<Self::Item> where Self::Item: Clone;
609 /// Creates an iterator that yields every possible permutation of the
610 /// vector in succession.
615 /// let v = [1, 2, 3];
616 /// let mut perms = v.permutations();
619 /// println!("{:?}", p);
623 /// Iterating through permutations one by one.
626 /// let v = [1, 2, 3];
627 /// let mut perms = v.permutations();
629 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
630 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
631 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
633 #[unstable(feature = "collections")]
634 fn permutations(&self) -> Permutations<Self::Item> where Self::Item: Clone;
636 /// Copies as many elements from `src` as it can into `self` (the
637 /// shorter of `self.len()` and `src.len()`). Returns the number
638 /// of elements copied.
643 /// let mut dst = [0, 0, 0];
644 /// let src = [1, 2];
646 /// assert!(dst.clone_from_slice(&src) == 2);
647 /// assert!(dst == [1, 2, 0]);
649 /// let src2 = [3, 4, 5, 6];
650 /// assert!(dst.clone_from_slice(&src2) == 3);
651 /// assert!(dst == [3, 4, 5]);
653 #[unstable(feature = "collections")]
654 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
656 /// Sorts the slice, in place.
658 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
663 /// let mut v = [-5, 4, 1, -3, 2];
666 /// assert!(v == [-5, -3, 1, 2, 4]);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn sort(&mut self) where Self::Item: Ord;
671 /// Binary search a sorted slice for a given element.
673 /// If the value is found then `Ok` is returned, containing the
674 /// index of the matching element; if the value is not found then
675 /// `Err` is returned, containing the index where a matching
676 /// element could be inserted while maintaining sorted order.
680 /// Looks up a series of four elements. The first is found, with a
681 /// uniquely determined position; the second and third are not
682 /// found; the fourth could match any position in `[1,4]`.
685 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
686 /// let s = s.as_slice();
688 /// assert_eq!(s.binary_search(&13), Ok(9));
689 /// assert_eq!(s.binary_search(&4), Err(7));
690 /// assert_eq!(s.binary_search(&100), Err(13));
691 /// let r = s.binary_search(&1);
692 /// assert!(match r { Ok(1...4) => true, _ => false, });
694 #[stable(feature = "rust1", since = "1.0.0")]
695 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
697 /// Deprecated: use `binary_search` instead.
698 #[unstable(feature = "collections")]
699 #[deprecated(since = "1.0.0", reason = "use binary_search instead")]
700 fn binary_search_elem(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord {
701 self.binary_search(x)
704 /// Mutates the slice to the next lexicographic permutation.
706 /// Returns `true` if successful and `false` if the slice is at the
707 /// last-ordered permutation.
712 /// let v: &mut [_] = &mut [0, 1, 2];
713 /// v.next_permutation();
714 /// let b: &mut [_] = &mut [0, 2, 1];
716 /// v.next_permutation();
717 /// let b: &mut [_] = &mut [1, 0, 2];
720 #[unstable(feature = "collections",
721 reason = "uncertain if this merits inclusion in std")]
722 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
724 /// Mutates the slice to the previous lexicographic permutation.
726 /// Returns `true` if successful and `false` if the slice is at the
727 /// first-ordered permutation.
732 /// let v: &mut [_] = &mut [1, 0, 2];
733 /// v.prev_permutation();
734 /// let b: &mut [_] = &mut [0, 2, 1];
736 /// v.prev_permutation();
737 /// let b: &mut [_] = &mut [0, 1, 2];
740 #[unstable(feature = "collections",
741 reason = "uncertain if this merits inclusion in std")]
742 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
744 /// Find the first index containing a matching value.
745 #[unstable(feature = "collections")]
746 fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
748 /// Find the last index containing a matching value.
749 #[unstable(feature = "collections")]
750 fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
752 /// Returns true if the slice contains an element with the given value.
757 /// let v = [10, 40, 30];
758 /// assert!(v.contains(&30));
759 /// assert!(!v.contains(&50));
761 #[stable(feature = "rust1", since = "1.0.0")]
762 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
764 /// Returns true if `needle` is a prefix of the slice.
769 /// let v = [10, 40, 30];
770 /// assert!(v.starts_with(&[10]));
771 /// assert!(v.starts_with(&[10, 40]));
772 /// assert!(!v.starts_with(&[50]));
773 /// assert!(!v.starts_with(&[10, 50]));
775 #[stable(feature = "rust1", since = "1.0.0")]
776 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
778 /// Returns true if `needle` is a suffix of the slice.
783 /// let v = [10, 40, 30];
784 /// assert!(v.ends_with(&[30]));
785 /// assert!(v.ends_with(&[40, 30]));
786 /// assert!(!v.ends_with(&[50]));
787 /// assert!(!v.ends_with(&[50, 30]));
789 #[stable(feature = "rust1", since = "1.0.0")]
790 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
792 /// Convert `self` into a vector without clones or allocation.
793 #[unstable(feature = "collections")]
794 fn into_vec(self: Box<Self>) -> Vec<Self::Item>;
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<T> SliceExt for [T] {
802 fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
803 merge_sort(self, compare)
807 fn move_from(&mut self, mut src: Vec<T>, start: usize, end: usize) -> usize {
808 for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) {
811 cmp::min(self.len(), end-start)
815 fn slice(&self, start: usize, end: usize) -> &[T] {
820 fn slice_from(&self, start: usize) -> &[T] {
825 fn slice_to(&self, end: usize) -> &[T] {
830 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
831 core_slice::SliceExt::split_at(self, mid)
835 fn iter(&self) -> Iter<T> {
836 core_slice::SliceExt::iter(self)
840 fn split<F>(&self, pred: F) -> Split<T, F>
841 where F: FnMut(&T) -> bool {
842 core_slice::SliceExt::split(self, pred)
846 fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
847 where F: FnMut(&T) -> bool {
848 core_slice::SliceExt::splitn(self, n, pred)
852 fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
853 where F: FnMut(&T) -> bool {
854 core_slice::SliceExt::rsplitn(self, n, pred)
858 fn windows(&self, size: usize) -> Windows<T> {
859 core_slice::SliceExt::windows(self, size)
863 fn chunks(&self, size: usize) -> Chunks<T> {
864 core_slice::SliceExt::chunks(self, size)
868 fn get(&self, index: usize) -> Option<&T> {
869 core_slice::SliceExt::get(self, index)
873 fn first(&self) -> Option<&T> {
874 core_slice::SliceExt::first(self)
878 fn tail(&self) -> &[T] {
879 core_slice::SliceExt::tail(self)
883 fn init(&self) -> &[T] {
884 core_slice::SliceExt::init(self)
888 fn last(&self) -> Option<&T> {
889 core_slice::SliceExt::last(self)
893 unsafe fn get_unchecked(&self, index: usize) -> &T {
894 core_slice::SliceExt::get_unchecked(self, index)
898 fn as_ptr(&self) -> *const T {
899 core_slice::SliceExt::as_ptr(self)
903 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
904 where F: FnMut(&T) -> Ordering {
905 core_slice::SliceExt::binary_search_by(self, f)
909 fn len(&self) -> usize {
910 core_slice::SliceExt::len(self)
914 fn is_empty(&self) -> bool {
915 core_slice::SliceExt::is_empty(self)
919 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
920 core_slice::SliceExt::get_mut(self, index)
924 fn as_mut_slice(&mut self) -> &mut [T] {
925 core_slice::SliceExt::as_mut_slice(self)
929 fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
930 &mut self[start .. end]
934 fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
939 fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
944 fn iter_mut(&mut self) -> IterMut<T> {
945 core_slice::SliceExt::iter_mut(self)
949 fn first_mut(&mut self) -> Option<&mut T> {
950 core_slice::SliceExt::first_mut(self)
954 fn tail_mut(&mut self) -> &mut [T] {
955 core_slice::SliceExt::tail_mut(self)
959 fn init_mut(&mut self) -> &mut [T] {
960 core_slice::SliceExt::init_mut(self)
964 fn last_mut(&mut self) -> Option<&mut T> {
965 core_slice::SliceExt::last_mut(self)
969 fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
970 where F: FnMut(&T) -> bool {
971 core_slice::SliceExt::split_mut(self, pred)
975 fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
976 where F: FnMut(&T) -> bool {
977 core_slice::SliceExt::splitn_mut(self, n, pred)
981 fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
982 where F: FnMut(&T) -> bool {
983 core_slice::SliceExt::rsplitn_mut(self, n, pred)
987 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
988 core_slice::SliceExt::chunks_mut(self, chunk_size)
992 fn swap(&mut self, a: usize, b: usize) {
993 core_slice::SliceExt::swap(self, a, b)
997 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
998 core_slice::SliceExt::split_at_mut(self, mid)
1002 fn reverse(&mut self) {
1003 core_slice::SliceExt::reverse(self)
1007 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
1008 core_slice::SliceExt::get_unchecked_mut(self, index)
1012 fn as_mut_ptr(&mut self) -> *mut T {
1013 core_slice::SliceExt::as_mut_ptr(self)
1016 /// Returns a copy of `v`.
1018 fn to_vec(&self) -> Vec<T> where T: Clone {
1019 let mut vector = Vec::with_capacity(self.len());
1020 vector.push_all(self);
1024 /// Returns an iterator over all permutations of a vector.
1025 fn permutations(&self) -> Permutations<T> where T: Clone {
1027 swaps: ElementSwaps::new(self.len()),
1032 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
1033 core_slice::SliceExt::clone_from_slice(self, src)
1037 fn sort(&mut self) where T: Ord {
1038 self.sort_by(|a, b| a.cmp(b))
1041 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
1042 core_slice::SliceExt::binary_search(self, x)
1045 fn next_permutation(&mut self) -> bool where T: Ord {
1046 core_slice::SliceExt::next_permutation(self)
1049 fn prev_permutation(&mut self) -> bool where T: Ord {
1050 core_slice::SliceExt::prev_permutation(self)
1053 fn position_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
1054 core_slice::SliceExt::position_elem(self, t)
1057 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
1058 core_slice::SliceExt::rposition_elem(self, t)
1061 fn contains(&self, x: &T) -> bool where T: PartialEq {
1062 core_slice::SliceExt::contains(self, x)
1065 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
1066 core_slice::SliceExt::starts_with(self, needle)
1069 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
1070 core_slice::SliceExt::ends_with(self, needle)
1073 fn into_vec(mut self: Box<Self>) -> Vec<T> {
1075 let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len());
1082 ////////////////////////////////////////////////////////////////////////////////
1083 // Extension traits for slices over specific kinds of data
1084 ////////////////////////////////////////////////////////////////////////////////
1085 #[unstable(feature = "collections", reason = "U should be an associated type")]
1086 /// An extension trait for concatenating slices
1087 pub trait SliceConcatExt<T: ?Sized, U> {
1088 /// Flattens a slice of `T` into a single value `U`.
1093 /// let v = vec!["hello", "world"];
1095 /// let s: String = v.concat();
1097 /// println!("{}", s); // prints "helloworld"
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 fn concat(&self) -> U;
1102 /// Flattens a slice of `T` into a single value `U`, placing a given separator between each.
1107 /// let v = vec!["hello", "world"];
1109 /// let s: String = v.connect(" ");
1111 /// println!("{}", s); // prints "hello world"
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 fn connect(&self, sep: &T) -> U;
1117 impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
1118 fn concat(&self) -> Vec<T> {
1119 let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
1120 let mut result = Vec::with_capacity(size);
1122 result.push_all(v.as_slice())
1127 fn connect(&self, sep: &T) -> Vec<T> {
1128 let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
1129 let mut result = Vec::with_capacity(size + self.len());
1130 let mut first = true;
1132 if first { first = false } else { result.push(sep.clone()) }
1133 result.push_all(v.as_slice())
1139 /// An iterator that yields the element swaps needed to produce
1140 /// a sequence of all possible permutations for an indexed sequence of
1141 /// elements. Each permutation is only a single swap apart.
1143 /// The Steinhaus-Johnson-Trotter algorithm is used.
1145 /// Generates even and odd permutations alternately.
1147 /// The last generated swap is always (0, 1), and it returns the
1148 /// sequence to its initial order.
1149 #[unstable(feature = "collections")]
1151 pub struct ElementSwaps {
1152 sdir: Vec<SizeDirection>,
1153 /// If `true`, emit the last swap that returns the sequence to initial
1160 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1161 #[unstable(feature = "collections")]
1162 pub fn new(length: usize) -> ElementSwaps {
1163 // Initialize `sdir` with a direction that position should move in
1164 // (all negative at the beginning) and the `size` of the
1165 // element (equal to the original index).
1168 sdir: (0..length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1174 ////////////////////////////////////////////////////////////////////////////////
1175 // Standard trait implementations for slices
1176 ////////////////////////////////////////////////////////////////////////////////
1178 #[unstable(feature = "collections", reason = "trait is unstable")]
1179 impl<T> BorrowFrom<Vec<T>> for [T] {
1180 fn borrow_from(owned: &Vec<T>) -> &[T] { &owned[] }
1183 #[unstable(feature = "collections", reason = "trait is unstable")]
1184 impl<T> BorrowFromMut<Vec<T>> for [T] {
1185 fn borrow_from_mut(owned: &mut Vec<T>) -> &mut [T] { &mut owned[] }
1188 #[unstable(feature = "collections", reason = "trait is unstable")]
1189 impl<T: Clone> ToOwned<Vec<T>> for [T] {
1190 fn to_owned(&self) -> Vec<T> { self.to_vec() }
1193 ////////////////////////////////////////////////////////////////////////////////
1195 ////////////////////////////////////////////////////////////////////////////////
1197 #[derive(Copy, Clone)]
1198 enum Direction { Pos, Neg }
1200 /// An `Index` and `Direction` together.
1201 #[derive(Copy, Clone)]
1202 struct SizeDirection {
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl Iterator for ElementSwaps {
1209 type Item = (usize, usize);
1212 fn next(&mut self) -> Option<(usize, usize)> {
1213 fn new_pos(i: usize, s: Direction) -> usize {
1214 i + match s { Pos => 1, Neg => -1 }
1217 // Find the index of the largest mobile element:
1218 // The direction should point into the vector, and the
1219 // swap should be with a smaller `size` element.
1220 let max = self.sdir.iter().cloned().enumerate()
1222 new_pos(i, sd.dir) < self.sdir.len() &&
1223 self.sdir[new_pos(i, sd.dir)].size < sd.size)
1224 .max_by(|&(_, sd)| sd.size);
1227 let j = new_pos(i, sd.dir);
1228 self.sdir.swap(i, j);
1230 // Swap the direction of each larger SizeDirection
1231 for x in &mut self.sdir {
1232 if x.size > sd.size {
1233 x.dir = match x.dir { Pos => Neg, Neg => Pos };
1236 self.swaps_made += 1;
1239 None => if self.emit_reset {
1240 self.emit_reset = false;
1241 if self.sdir.len() > 1 {
1243 self.swaps_made += 1;
1246 // Vector is of the form [] or [x], and the only permutation is itself
1247 self.swaps_made += 1;
1255 fn size_hint(&self) -> (usize, Option<usize>) {
1256 // For a vector of size n, there are exactly n! permutations.
1257 let n = (2..self.sdir.len() + 1).product();
1258 (n - self.swaps_made, Some(n - self.swaps_made))
1262 /// An iterator that uses `ElementSwaps` to iterate through
1263 /// all possible permutations of a vector.
1265 /// The first iteration yields a clone of the vector as it is,
1266 /// then each successive element is the vector with one
1269 /// Generates even and odd permutations alternately.
1270 #[unstable(feature = "collections")]
1271 pub struct Permutations<T> {
1272 swaps: ElementSwaps,
1276 #[unstable(feature = "collections", reason = "trait is unstable")]
1277 impl<T: Clone> Iterator for Permutations<T> {
1281 fn next(&mut self) -> Option<Vec<T>> {
1282 match self.swaps.next() {
1284 Some((0,0)) => Some(self.v.clone()),
1286 let elt = self.v.clone();
1294 fn size_hint(&self) -> (usize, Option<usize>) {
1295 self.swaps.size_hint()
1299 ////////////////////////////////////////////////////////////////////////////////
1301 ////////////////////////////////////////////////////////////////////////////////
1303 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1304 let len = v.len() as isize;
1305 let buf_v = v.as_mut_ptr();
1309 // j satisfies: 0 <= j <= i;
1312 // `i` is in bounds.
1313 let read_ptr = buf_v.offset(i) as *const T;
1315 // find where to insert, we need to do strict <,
1316 // rather than <=, to maintain stability.
1318 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1320 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1324 // shift everything to the right, to make space to
1325 // insert this value.
1327 // j + 1 could be `len` (for the last `i`), but in
1328 // that case, `i == j` so we don't copy. The
1329 // `.offset(j)` is always in bounds.
1332 let tmp = ptr::read(read_ptr);
1333 ptr::copy_memory(buf_v.offset(j + 1),
1336 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
1345 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1346 // warning: this wildly uses unsafe.
1347 static BASE_INSERTION: usize = 32;
1348 static LARGE_INSERTION: usize = 16;
1350 // FIXME #12092: smaller insertion runs seems to make sorting
1351 // vectors of large elements a little faster on some platforms,
1352 // but hasn't been tested/tuned extensively
1353 let insertion = if size_of::<T>() <= 16 {
1361 // short vectors get sorted in-place via insertion sort to avoid allocations
1362 if len <= insertion {
1363 insertion_sort(v, compare);
1367 // allocate some memory to use as scratch memory, we keep the
1368 // length 0 so we can keep shallow copies of the contents of `v`
1369 // without risking the dtors running on an object twice if
1370 // `compare` panics.
1371 let mut working_space = Vec::with_capacity(2 * len);
1372 // these both are buffers of length `len`.
1373 let mut buf_dat = working_space.as_mut_ptr();
1374 let mut buf_tmp = unsafe {buf_dat.offset(len as isize)};
1377 let buf_v = v.as_ptr();
1379 // step 1. sort short runs with insertion sort. This takes the
1380 // values from `v` and sorts them into `buf_dat`, leaving that
1381 // with sorted runs of length INSERTION.
1383 // We could hardcode the sorting comparisons here, and we could
1384 // manipulate/step the pointers themselves, rather than repeatedly
1386 for start in range_step(0, len, insertion) {
1387 // start <= i < len;
1388 for i in start..cmp::min(start + insertion, len) {
1389 // j satisfies: start <= j <= i;
1390 let mut j = i as isize;
1392 // `i` is in bounds.
1393 let read_ptr = buf_v.offset(i as isize);
1395 // find where to insert, we need to do strict <,
1396 // rather than <=, to maintain stability.
1398 // start <= j - 1 < len, so .offset(j - 1) is in
1400 while j > start as isize &&
1401 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1405 // shift everything to the right, to make space to
1406 // insert this value.
1408 // j + 1 could be `len` (for the last `i`), but in
1409 // that case, `i == j` so we don't copy. The
1410 // `.offset(j)` is always in bounds.
1411 ptr::copy_memory(buf_dat.offset(j + 1),
1412 &*buf_dat.offset(j),
1414 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1419 // step 2. merge the sorted runs.
1420 let mut width = insertion;
1422 // merge the sorted runs of length `width` in `buf_dat` two at
1423 // a time, placing the result in `buf_tmp`.
1425 // 0 <= start <= len.
1426 for start in range_step(0, len, 2 * width) {
1427 // manipulate pointers directly for speed (rather than
1428 // using a `for` loop with `range` and `.offset` inside
1431 // the end of the first run & start of the
1432 // second. Offset of `len` is defined, since this is
1433 // precisely one byte past the end of the object.
1434 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1435 // end of the second. Similar reasoning to the above re safety.
1436 let right_end_idx = cmp::min(start + 2 * width, len);
1437 let right_end = buf_dat.offset(right_end_idx as isize);
1439 // the pointers to the elements under consideration
1440 // from the two runs.
1442 // both of these are in bounds.
1443 let mut left = buf_dat.offset(start as isize);
1444 let mut right = right_start;
1446 // where we're putting the results, it is a run of
1447 // length `2*width`, so we step it once for each step
1448 // of either `left` or `right`. `buf_tmp` has length
1449 // `len`, so these are in bounds.
1450 let mut out = buf_tmp.offset(start as isize);
1451 let out_end = buf_tmp.offset(right_end_idx as isize);
1453 while out < out_end {
1454 // Either the left or the right run are exhausted,
1455 // so just copy the remainder from the other run
1456 // and move on; this gives a huge speed-up (order
1457 // of 25%) for mostly sorted vectors (the best
1459 if left == right_start {
1460 // the number remaining in this run.
1461 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1462 ptr::copy_nonoverlapping_memory(out, &*right, elems);
1464 } else if right == right_end {
1465 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1466 ptr::copy_nonoverlapping_memory(out, &*left, elems);
1470 // check which side is smaller, and that's the
1471 // next element for the new run.
1473 // `left < right_start` and `right < right_end`,
1474 // so these are valid.
1475 let to_copy = if compare(&*left, &*right) == Greater {
1480 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
1486 mem::swap(&mut buf_dat, &mut buf_tmp);
1491 // write the result to `v` in one go, so that there are never two copies
1492 // of the same object in `v`.
1494 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
1497 // increment the pointer, returning the old pointer.
1499 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1501 *ptr = ptr.offset(1);
1508 use core::cmp::Ordering::{Greater, Less, Equal};
1509 use core::prelude::{Some, None, Clone};
1510 use core::prelude::{Iterator, IteratorExt};
1511 use core::prelude::{AsSlice};
1512 use core::prelude::Ord;
1513 use core::default::Default;
1515 use std::iter::RandomAccessIterator;
1516 use std::rand::{Rng, thread_rng};
1518 use string::ToString;
1520 use super::{ElementSwaps, SliceConcatExt, SliceExt};
1522 fn square(n: usize) -> usize { n * n }
1524 fn is_odd(n: &usize) -> bool { *n % 2 == 1 }
1528 // Test on-stack from_fn.
1529 let mut v: Vec<_> = (0..3).map(square).collect();
1532 assert_eq!(v.len(), 3);
1533 assert_eq!(v[0], 0);
1534 assert_eq!(v[1], 1);
1535 assert_eq!(v[2], 4);
1538 // Test on-heap from_fn.
1539 v = (0..5).map(square).collect();
1542 assert_eq!(v.len(), 5);
1543 assert_eq!(v[0], 0);
1544 assert_eq!(v[1], 1);
1545 assert_eq!(v[2], 4);
1546 assert_eq!(v[3], 9);
1547 assert_eq!(v[4], 16);
1552 fn test_from_elem() {
1553 // Test on-stack from_elem.
1554 let mut v = vec![10, 10];
1557 assert_eq!(v.len(), 2);
1558 assert_eq!(v[0], 10);
1559 assert_eq!(v[1], 10);
1562 // Test on-heap from_elem.
1565 let v = v.as_slice();
1566 assert_eq!(v[0], 20);
1567 assert_eq!(v[1], 20);
1568 assert_eq!(v[2], 20);
1569 assert_eq!(v[3], 20);
1570 assert_eq!(v[4], 20);
1571 assert_eq!(v[5], 20);
1576 fn test_is_empty() {
1577 let xs: [i32; 0] = [];
1578 assert!(xs.is_empty());
1579 assert!(![0].is_empty());
1583 fn test_len_divzero() {
1585 let v0 : &[Z] = &[];
1586 let v1 : &[Z] = &[[]];
1587 let v2 : &[Z] = &[[], []];
1588 assert_eq!(mem::size_of::<Z>(), 0);
1589 assert_eq!(v0.len(), 0);
1590 assert_eq!(v1.len(), 1);
1591 assert_eq!(v2.len(), 2);
1596 let mut a = vec![11];
1597 assert_eq!(a.get(1), None);
1599 assert_eq!(a.get(1).unwrap(), &12);
1600 a = vec![11, 12, 13];
1601 assert_eq!(a.get(1).unwrap(), &12);
1607 assert_eq!(a.first(), None);
1609 assert_eq!(a.first().unwrap(), &11);
1611 assert_eq!(a.first().unwrap(), &11);
1615 fn test_first_mut() {
1617 assert_eq!(a.first_mut(), None);
1619 assert_eq!(*a.first_mut().unwrap(), 11);
1621 assert_eq!(*a.first_mut().unwrap(), 11);
1626 let mut a = vec![11];
1627 let b: &[i32] = &[];
1628 assert_eq!(a.tail(), b);
1630 let b: &[i32] = &[12];
1631 assert_eq!(a.tail(), b);
1635 fn test_tail_mut() {
1636 let mut a = vec![11];
1637 let b: &mut [i32] = &mut [];
1638 assert!(a.tail_mut() == b);
1640 let b: &mut [_] = &mut [12];
1641 assert!(a.tail_mut() == b);
1646 fn test_tail_empty() {
1647 let a = Vec::<i32>::new();
1653 fn test_tail_mut_empty() {
1654 let mut a = Vec::<i32>::new();
1660 let mut a = vec![11];
1661 let b: &[i32] = &[];
1662 assert_eq!(a.init(), b);
1664 let b: &[_] = &[11];
1665 assert_eq!(a.init(), b);
1669 fn test_init_mut() {
1670 let mut a = vec![11];
1671 let b: &mut [i32] = &mut [];
1672 assert!(a.init_mut() == b);
1674 let b: &mut [_] = &mut [11];
1675 assert!(a.init_mut() == b);
1680 fn test_init_empty() {
1681 let a = Vec::<i32>::new();
1687 fn test_init_mut_empty() {
1688 let mut a = Vec::<i32>::new();
1695 assert_eq!(a.last(), None);
1697 assert_eq!(a.last().unwrap(), &11);
1699 assert_eq!(a.last().unwrap(), &12);
1703 fn test_last_mut() {
1705 assert_eq!(a.last_mut(), None);
1707 assert_eq!(*a.last_mut().unwrap(), 11);
1709 assert_eq!(*a.last_mut().unwrap(), 12);
1714 // Test fixed length vector.
1715 let vec_fixed = [1, 2, 3, 4];
1716 let v_a = vec_fixed[1..vec_fixed.len()].to_vec();
1717 assert_eq!(v_a.len(), 3);
1719 assert_eq!(v_a[0], 2);
1720 assert_eq!(v_a[1], 3);
1721 assert_eq!(v_a[2], 4);
1724 let vec_stack: &[_] = &[1, 2, 3];
1725 let v_b = vec_stack[1..3].to_vec();
1726 assert_eq!(v_b.len(), 2);
1728 assert_eq!(v_b[0], 2);
1729 assert_eq!(v_b[1], 3);
1732 let vec_unique = vec![1, 2, 3, 4, 5, 6];
1733 let v_d = vec_unique[1..6].to_vec();
1734 assert_eq!(v_d.len(), 5);
1736 assert_eq!(v_d[0], 2);
1737 assert_eq!(v_d[1], 3);
1738 assert_eq!(v_d[2], 4);
1739 assert_eq!(v_d[3], 5);
1740 assert_eq!(v_d[4], 6);
1744 fn test_slice_from() {
1745 let vec: &[_] = &[1, 2, 3, 4];
1746 assert_eq!(&vec[], vec);
1747 let b: &[_] = &[3, 4];
1748 assert_eq!(&vec[2..], b);
1750 assert_eq!(&vec[4..], b);
1754 fn test_slice_to() {
1755 let vec: &[_] = &[1, 2, 3, 4];
1756 assert_eq!(&vec[..4], vec);
1757 let b: &[_] = &[1, 2];
1758 assert_eq!(&vec[..2], b);
1760 assert_eq!(&vec[..0], b);
1766 let mut v = vec![5];
1768 assert_eq!(v.len(), 0);
1769 assert_eq!(e, Some(5));
1771 assert_eq!(f, None);
1773 assert_eq!(g, None);
1777 fn test_swap_remove() {
1778 let mut v = vec![1, 2, 3, 4, 5];
1779 let mut e = v.swap_remove(0);
1781 assert_eq!(v, vec![5, 2, 3, 4]);
1782 e = v.swap_remove(3);
1784 assert_eq!(v, vec![5, 2, 3]);
1789 fn test_swap_remove_fail() {
1790 let mut v = vec![1];
1791 let _ = v.swap_remove(0);
1792 let _ = v.swap_remove(0);
1796 fn test_swap_remove_noncopyable() {
1797 // Tests that we don't accidentally run destructors twice.
1798 let mut v = Vec::new();
1802 let mut _e = v.swap_remove(0);
1803 assert_eq!(v.len(), 2);
1804 _e = v.swap_remove(1);
1805 assert_eq!(v.len(), 1);
1806 _e = v.swap_remove(0);
1807 assert_eq!(v.len(), 0);
1812 // Test on-stack push().
1815 assert_eq!(v.len(), 1);
1816 assert_eq!(v[0], 1);
1818 // Test on-heap push().
1820 assert_eq!(v.len(), 2);
1821 assert_eq!(v[0], 1);
1822 assert_eq!(v[1], 2);
1826 fn test_truncate() {
1827 let mut v = vec![box 6,box 5,box 4];
1830 assert_eq!(v.len(), 1);
1831 assert_eq!(*(v[0]), 6);
1832 // If the unsafe block didn't drop things properly, we blow up here.
1837 let mut v = vec![box 6,box 5,box 4];
1839 assert_eq!(v.len(), 0);
1840 // If the unsafe block didn't drop things properly, we blow up here.
1845 fn case(a: Vec<i32>, b: Vec<i32>) {
1850 case(vec![], vec![]);
1851 case(vec![1], vec![1]);
1852 case(vec![1,1], vec![1]);
1853 case(vec![1,2,3], vec![1,2,3]);
1854 case(vec![1,1,2,3], vec![1,2,3]);
1855 case(vec![1,2,2,3], vec![1,2,3]);
1856 case(vec![1,2,3,3], vec![1,2,3]);
1857 case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
1861 fn test_dedup_unique() {
1862 let mut v0 = vec![box 1, box 1, box 2, box 3];
1864 let mut v1 = vec![box 1, box 2, box 2, box 3];
1866 let mut v2 = vec![box 1, box 2, box 3, box 3];
1869 * If the boxed pointers were leaked or otherwise misused, valgrind
1870 * and/or rt should raise errors.
1875 fn test_dedup_shared() {
1876 let mut v0 = vec![box 1, box 1, box 2, box 3];
1878 let mut v1 = vec![box 1, box 2, box 2, box 3];
1880 let mut v2 = vec![box 1, box 2, box 3, box 3];
1883 * If the pointers were leaked or otherwise misused, valgrind and/or
1884 * rt should raise errors.
1890 let mut v = vec![1, 2, 3, 4, 5];
1892 assert_eq!(v, vec![1, 3, 5]);
1896 fn test_element_swaps() {
1897 let mut v = [1, 2, 3];
1898 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1901 0 => assert!(v == [1, 3, 2]),
1902 1 => assert!(v == [3, 1, 2]),
1903 2 => assert!(v == [3, 2, 1]),
1904 3 => assert!(v == [2, 3, 1]),
1905 4 => assert!(v == [2, 1, 3]),
1906 5 => assert!(v == [1, 2, 3]),
1913 fn test_permutations() {
1915 let v: [i32; 0] = [];
1916 let mut it = v.permutations();
1917 let (min_size, max_opt) = it.size_hint();
1918 assert_eq!(min_size, 1);
1919 assert_eq!(max_opt.unwrap(), 1);
1920 assert_eq!(it.next(), Some(v.to_vec()));
1921 assert_eq!(it.next(), None);
1924 let v = ["Hello".to_string()];
1925 let mut it = v.permutations();
1926 let (min_size, max_opt) = it.size_hint();
1927 assert_eq!(min_size, 1);
1928 assert_eq!(max_opt.unwrap(), 1);
1929 assert_eq!(it.next(), Some(v.to_vec()));
1930 assert_eq!(it.next(), None);
1934 let mut it = v.permutations();
1935 let (min_size, max_opt) = it.size_hint();
1936 assert_eq!(min_size, 3*2);
1937 assert_eq!(max_opt.unwrap(), 3*2);
1938 assert_eq!(it.next(), Some(vec![1,2,3]));
1939 assert_eq!(it.next(), Some(vec![1,3,2]));
1940 assert_eq!(it.next(), Some(vec![3,1,2]));
1941 let (min_size, max_opt) = it.size_hint();
1942 assert_eq!(min_size, 3);
1943 assert_eq!(max_opt.unwrap(), 3);
1944 assert_eq!(it.next(), Some(vec![3,2,1]));
1945 assert_eq!(it.next(), Some(vec![2,3,1]));
1946 assert_eq!(it.next(), Some(vec![2,1,3]));
1947 assert_eq!(it.next(), None);
1950 // check that we have N! permutations
1951 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1953 let mut it = v.permutations();
1954 let (min_size, max_opt) = it.size_hint();
1955 for _perm in it.by_ref() {
1958 assert_eq!(amt, it.swaps.swaps_made);
1959 assert_eq!(amt, min_size);
1960 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1961 assert_eq!(amt, max_opt.unwrap());
1966 fn test_lexicographic_permutations() {
1967 let v : &mut[_] = &mut[1, 2, 3, 4, 5];
1968 assert!(v.prev_permutation() == false);
1969 assert!(v.next_permutation());
1970 let b: &mut[_] = &mut[1, 2, 3, 5, 4];
1972 assert!(v.prev_permutation());
1973 let b: &mut[_] = &mut[1, 2, 3, 4, 5];
1975 assert!(v.next_permutation());
1976 assert!(v.next_permutation());
1977 let b: &mut[_] = &mut[1, 2, 4, 3, 5];
1979 assert!(v.next_permutation());
1980 let b: &mut[_] = &mut[1, 2, 4, 5, 3];
1983 let v : &mut[_] = &mut[1, 0, 0, 0];
1984 assert!(v.next_permutation() == false);
1985 assert!(v.prev_permutation());
1986 let b: &mut[_] = &mut[0, 1, 0, 0];
1988 assert!(v.prev_permutation());
1989 let b: &mut[_] = &mut[0, 0, 1, 0];
1991 assert!(v.prev_permutation());
1992 let b: &mut[_] = &mut[0, 0, 0, 1];
1994 assert!(v.prev_permutation() == false);
1998 fn test_lexicographic_permutations_empty_and_short() {
1999 let empty : &mut[i32] = &mut[];
2000 assert!(empty.next_permutation() == false);
2001 let b: &mut[i32] = &mut[];
2002 assert!(empty == b);
2003 assert!(empty.prev_permutation() == false);
2004 assert!(empty == b);
2006 let one_elem : &mut[_] = &mut[4];
2007 assert!(one_elem.prev_permutation() == false);
2008 let b: &mut[_] = &mut[4];
2009 assert!(one_elem == b);
2010 assert!(one_elem.next_permutation() == false);
2011 assert!(one_elem == b);
2013 let two_elem : &mut[_] = &mut[1, 2];
2014 assert!(two_elem.prev_permutation() == false);
2015 let b : &mut[_] = &mut[1, 2];
2016 let c : &mut[_] = &mut[2, 1];
2017 assert!(two_elem == b);
2018 assert!(two_elem.next_permutation());
2019 assert!(two_elem == c);
2020 assert!(two_elem.next_permutation() == false);
2021 assert!(two_elem == c);
2022 assert!(two_elem.prev_permutation());
2023 assert!(two_elem == b);
2024 assert!(two_elem.prev_permutation() == false);
2025 assert!(two_elem == b);
2029 fn test_position_elem() {
2030 assert!([].position_elem(&1).is_none());
2032 let v1 = vec![1, 2, 3, 3, 2, 5];
2033 assert_eq!(v1.position_elem(&1), Some(0));
2034 assert_eq!(v1.position_elem(&2), Some(1));
2035 assert_eq!(v1.position_elem(&5), Some(5));
2036 assert!(v1.position_elem(&4).is_none());
2040 fn test_binary_search() {
2041 assert_eq!([1,2,3,4,5].binary_search(&5).ok(), Some(4));
2042 assert_eq!([1,2,3,4,5].binary_search(&4).ok(), Some(3));
2043 assert_eq!([1,2,3,4,5].binary_search(&3).ok(), Some(2));
2044 assert_eq!([1,2,3,4,5].binary_search(&2).ok(), Some(1));
2045 assert_eq!([1,2,3,4,5].binary_search(&1).ok(), Some(0));
2047 assert_eq!([2,4,6,8,10].binary_search(&1).ok(), None);
2048 assert_eq!([2,4,6,8,10].binary_search(&5).ok(), None);
2049 assert_eq!([2,4,6,8,10].binary_search(&4).ok(), Some(1));
2050 assert_eq!([2,4,6,8,10].binary_search(&10).ok(), Some(4));
2052 assert_eq!([2,4,6,8].binary_search(&1).ok(), None);
2053 assert_eq!([2,4,6,8].binary_search(&5).ok(), None);
2054 assert_eq!([2,4,6,8].binary_search(&4).ok(), Some(1));
2055 assert_eq!([2,4,6,8].binary_search(&8).ok(), Some(3));
2057 assert_eq!([2,4,6].binary_search(&1).ok(), None);
2058 assert_eq!([2,4,6].binary_search(&5).ok(), None);
2059 assert_eq!([2,4,6].binary_search(&4).ok(), Some(1));
2060 assert_eq!([2,4,6].binary_search(&6).ok(), Some(2));
2062 assert_eq!([2,4].binary_search(&1).ok(), None);
2063 assert_eq!([2,4].binary_search(&5).ok(), None);
2064 assert_eq!([2,4].binary_search(&2).ok(), Some(0));
2065 assert_eq!([2,4].binary_search(&4).ok(), Some(1));
2067 assert_eq!([2].binary_search(&1).ok(), None);
2068 assert_eq!([2].binary_search(&5).ok(), None);
2069 assert_eq!([2].binary_search(&2).ok(), Some(0));
2071 assert_eq!([].binary_search(&1).ok(), None);
2072 assert_eq!([].binary_search(&5).ok(), None);
2074 assert!([1,1,1,1,1].binary_search(&1).ok() != None);
2075 assert!([1,1,1,1,2].binary_search(&1).ok() != None);
2076 assert!([1,1,1,2,2].binary_search(&1).ok() != None);
2077 assert!([1,1,2,2,2].binary_search(&1).ok() != None);
2078 assert_eq!([1,2,2,2,2].binary_search(&1).ok(), Some(0));
2080 assert_eq!([1,2,3,4,5].binary_search(&6).ok(), None);
2081 assert_eq!([1,2,3,4,5].binary_search(&0).ok(), None);
2086 let mut v = vec![10, 20];
2087 assert_eq!(v[0], 10);
2088 assert_eq!(v[1], 20);
2090 assert_eq!(v[0], 20);
2091 assert_eq!(v[1], 10);
2093 let mut v3 = Vec::<i32>::new();
2095 assert!(v3.is_empty());
2102 let mut v: Vec<_> = thread_rng().gen_iter::<i32>().take(len).collect();
2103 let mut v1 = v.clone();
2106 assert!(v.windows(2).all(|w| w[0] <= w[1]));
2108 v1.sort_by(|a, b| a.cmp(b));
2109 assert!(v1.windows(2).all(|w| w[0] <= w[1]));
2111 v1.sort_by(|a, b| b.cmp(a));
2112 assert!(v1.windows(2).all(|w| w[0] >= w[1]));
2117 let mut v: [i32; 0] = [];
2120 let mut v = [0xDEADBEEFu64];
2122 assert!(v == [0xDEADBEEF]);
2126 fn test_sort_stability() {
2129 let mut counts = [0; 10];
2131 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
2132 // where the first item of each tuple is random, but
2133 // the second item represents which occurrence of that
2134 // number this element is, i.e. the second elements
2135 // will occur in sorted order.
2136 let mut v: Vec<_> = (0..len).map(|_| {
2137 let n = thread_rng().gen::<usize>() % 10;
2142 // only sort on the first element, so an unstable sort
2143 // may mix up the counts.
2144 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
2146 // this comparison includes the count (the second item
2147 // of the tuple), so elements with equal first items
2148 // will need to be ordered with increasing
2149 // counts... i.e. exactly asserting that this sort is
2151 assert!(v.windows(2).all(|w| w[0] <= w[1]));
2158 let v: [Vec<i32>; 0] = [];
2161 let d = [vec![1], vec![2,3]].concat();
2162 assert_eq!(d, vec![1, 2, 3]);
2164 let v: &[&[_]] = &[&[1], &[2, 3]];
2165 assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
2166 let v: &[&[_]] = &[&[1], &[2], &[3]];
2167 assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
2172 let v: [Vec<i32>; 0] = [];
2173 assert_eq!(v.connect(&0), vec![]);
2174 assert_eq!([vec![1], vec![2, 3]].connect(&0), vec![1, 0, 2, 3]);
2175 assert_eq!([vec![1], vec![2], vec![3]].connect(&0), vec![1, 0, 2, 0, 3]);
2177 let v: [&[_]; 2] = [&[1], &[2, 3]];
2178 assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
2179 let v: [&[_]; 3] = [&[1], &[2], &[3]];
2180 assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
2185 let mut a = vec![1, 2, 4];
2187 assert_eq!(a, vec![1, 2, 3, 4]);
2189 let mut a = vec![1, 2, 3];
2191 assert_eq!(a, vec![0, 1, 2, 3]);
2193 let mut a = vec![1, 2, 3];
2195 assert_eq!(a, vec![1, 2, 3, 4]);
2199 assert_eq!(a, vec![1]);
2204 fn test_insert_oob() {
2205 let mut a = vec![1, 2, 3];
2211 let mut a = vec![1, 2, 3, 4];
2213 assert_eq!(a.remove(2), 3);
2214 assert_eq!(a, vec![1, 2, 4]);
2216 assert_eq!(a.remove(2), 4);
2217 assert_eq!(a, vec![1, 2]);
2219 assert_eq!(a.remove(0), 1);
2220 assert_eq!(a, vec![2]);
2222 assert_eq!(a.remove(0), 2);
2223 assert_eq!(a, vec![]);
2228 fn test_remove_fail() {
2229 let mut a = vec![1];
2230 let _ = a.remove(0);
2231 let _ = a.remove(0);
2235 fn test_capacity() {
2236 let mut v = vec![0];
2237 v.reserve_exact(10);
2238 assert!(v.capacity() >= 11);
2243 let v = vec![1, 2, 3, 4, 5];
2244 let v = v.slice(1, 3);
2245 assert_eq!(v.len(), 2);
2246 assert_eq!(v[0], 2);
2247 assert_eq!(v[1], 3);
2252 fn test_permute_fail() {
2253 let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
2254 (box 0, Rc::new(0)), (box 0, Rc::new(0))];
2256 for _ in v.permutations() {
2265 fn test_total_ord() {
2267 [1, 2, 3, 4][].cmp(c) == Greater;
2268 let c = &[1, 2, 3, 4];
2269 [1, 2, 3][].cmp(c) == Less;
2270 let c = &[1, 2, 3, 6];
2271 [1, 2, 3, 4][].cmp(c) == Equal;
2272 let c = &[1, 2, 3, 4, 5, 6];
2273 [1, 2, 3, 4, 5, 5, 5, 5][].cmp(c) == Less;
2274 let c = &[1, 2, 3, 4];
2275 [2, 2][].cmp(c) == Greater;
2279 fn test_iterator() {
2280 let xs = [1, 2, 5, 10, 11];
2281 let mut it = xs.iter();
2282 assert_eq!(it.size_hint(), (5, Some(5)));
2283 assert_eq!(it.next().unwrap(), &1);
2284 assert_eq!(it.size_hint(), (4, Some(4)));
2285 assert_eq!(it.next().unwrap(), &2);
2286 assert_eq!(it.size_hint(), (3, Some(3)));
2287 assert_eq!(it.next().unwrap(), &5);
2288 assert_eq!(it.size_hint(), (2, Some(2)));
2289 assert_eq!(it.next().unwrap(), &10);
2290 assert_eq!(it.size_hint(), (1, Some(1)));
2291 assert_eq!(it.next().unwrap(), &11);
2292 assert_eq!(it.size_hint(), (0, Some(0)));
2293 assert!(it.next().is_none());
2297 fn test_random_access_iterator() {
2298 let xs = [1, 2, 5, 10, 11];
2299 let mut it = xs.iter();
2301 assert_eq!(it.indexable(), 5);
2302 assert_eq!(it.idx(0).unwrap(), &1);
2303 assert_eq!(it.idx(2).unwrap(), &5);
2304 assert_eq!(it.idx(4).unwrap(), &11);
2305 assert!(it.idx(5).is_none());
2307 assert_eq!(it.next().unwrap(), &1);
2308 assert_eq!(it.indexable(), 4);
2309 assert_eq!(it.idx(0).unwrap(), &2);
2310 assert_eq!(it.idx(3).unwrap(), &11);
2311 assert!(it.idx(4).is_none());
2313 assert_eq!(it.next().unwrap(), &2);
2314 assert_eq!(it.indexable(), 3);
2315 assert_eq!(it.idx(1).unwrap(), &10);
2316 assert!(it.idx(3).is_none());
2318 assert_eq!(it.next().unwrap(), &5);
2319 assert_eq!(it.indexable(), 2);
2320 assert_eq!(it.idx(1).unwrap(), &11);
2322 assert_eq!(it.next().unwrap(), &10);
2323 assert_eq!(it.indexable(), 1);
2324 assert_eq!(it.idx(0).unwrap(), &11);
2325 assert!(it.idx(1).is_none());
2327 assert_eq!(it.next().unwrap(), &11);
2328 assert_eq!(it.indexable(), 0);
2329 assert!(it.idx(0).is_none());
2331 assert!(it.next().is_none());
2335 fn test_iter_size_hints() {
2336 let mut xs = [1, 2, 5, 10, 11];
2337 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
2338 assert_eq!(xs.iter_mut().size_hint(), (5, Some(5)));
2342 fn test_iter_clone() {
2344 let mut it = xs.iter();
2346 let mut jt = it.clone();
2347 assert_eq!(it.next(), jt.next());
2348 assert_eq!(it.next(), jt.next());
2349 assert_eq!(it.next(), jt.next());
2353 fn test_mut_iterator() {
2354 let mut xs = [1, 2, 3, 4, 5];
2358 assert!(xs == [2, 3, 4, 5, 6])
2362 fn test_rev_iterator() {
2364 let xs = [1, 2, 5, 10, 11];
2365 let ys = [11, 10, 5, 2, 1];
2367 for &x in xs.iter().rev() {
2368 assert_eq!(x, ys[i]);
2375 fn test_mut_rev_iterator() {
2376 let mut xs = [1, 2, 3, 4, 5];
2377 for (i,x) in xs.iter_mut().rev().enumerate() {
2380 assert!(xs == [5, 5, 5, 5, 5])
2384 fn test_move_iterator() {
2385 let xs = vec![1,2,3,4,5];
2386 assert_eq!(xs.into_iter().fold(0, |a: usize, b: usize| 10*a + b), 12345);
2390 fn test_move_rev_iterator() {
2391 let xs = vec![1,2,3,4,5];
2392 assert_eq!(xs.into_iter().rev().fold(0, |a: usize, b: usize| 10*a + b), 54321);
2396 fn test_splitator() {
2397 let xs = &[1,2,3,4,5];
2399 let splits: &[&[_]] = &[&[1], &[3], &[5]];
2400 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<_>>(),
2402 let splits: &[&[_]] = &[&[], &[2,3,4,5]];
2403 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<_>>(),
2405 let splits: &[&[_]] = &[&[1,2,3,4], &[]];
2406 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<_>>(),
2408 let splits: &[&[_]] = &[&[1,2,3,4,5]];
2409 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<_>>(),
2411 let splits: &[&[_]] = &[&[], &[], &[], &[], &[], &[]];
2412 assert_eq!(xs.split(|_| true).collect::<Vec<&[i32]>>(),
2415 let xs: &[i32] = &[];
2416 let splits: &[&[i32]] = &[&[]];
2417 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[i32]>>(), splits);
2421 fn test_splitnator() {
2422 let xs = &[1,2,3,4,5];
2424 let splits: &[&[_]] = &[&[1,2,3,4,5]];
2425 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2427 let splits: &[&[_]] = &[&[1], &[3,4,5]];
2428 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2430 let splits: &[&[_]] = &[&[], &[], &[], &[4,5]];
2431 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<_>>(),
2434 let xs: &[i32] = &[];
2435 let splits: &[&[i32]] = &[&[]];
2436 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<_>>(), splits);
2440 fn test_splitnator_mut() {
2441 let xs = &mut [1,2,3,4,5];
2443 let splits: &[&mut[_]] = &[&mut [1,2,3,4,5]];
2444 assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2446 let splits: &[&mut[_]] = &[&mut [1], &mut [3,4,5]];
2447 assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2449 let splits: &[&mut[_]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
2450 assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<_>>(),
2453 let xs: &mut [i32] = &mut [];
2454 let splits: &[&mut[i32]] = &[&mut []];
2455 assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<_>>(),
2460 fn test_rsplitator() {
2461 let xs = &[1,2,3,4,5];
2463 let splits: &[&[_]] = &[&[5], &[3], &[1]];
2464 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<_>>(),
2466 let splits: &[&[_]] = &[&[2,3,4,5], &[]];
2467 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<_>>(),
2469 let splits: &[&[_]] = &[&[], &[1,2,3,4]];
2470 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<_>>(),
2472 let splits: &[&[_]] = &[&[1,2,3,4,5]];
2473 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<_>>(),
2476 let xs: &[i32] = &[];
2477 let splits: &[&[i32]] = &[&[]];
2478 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[i32]>>(), splits);
2482 fn test_rsplitnator() {
2483 let xs = &[1,2,3,4,5];
2485 let splits: &[&[_]] = &[&[1,2,3,4,5]];
2486 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2488 let splits: &[&[_]] = &[&[5], &[1,2,3]];
2489 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2491 let splits: &[&[_]] = &[&[], &[], &[], &[1,2]];
2492 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<_>>(),
2495 let xs: &[i32] = &[];
2496 let splits: &[&[i32]] = &[&[]];
2497 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[i32]>>(), splits);
2501 fn test_windowsator() {
2504 let wins: &[&[_]] = &[&[1,2], &[2,3], &[3,4]];
2505 assert_eq!(v.windows(2).collect::<Vec<_>>(), wins);
2507 let wins: &[&[_]] = &[&[1,2,3], &[2,3,4]];
2508 assert_eq!(v.windows(3).collect::<Vec<_>>(), wins);
2509 assert!(v.windows(6).next().is_none());
2511 let wins: &[&[_]] = &[&[3,4], &[2,3], &[1,2]];
2512 assert_eq!(v.windows(2).rev().collect::<Vec<&[_]>>(), wins);
2513 let mut it = v.windows(2);
2514 assert_eq!(it.indexable(), 3);
2515 let win: &[_] = &[1,2];
2516 assert_eq!(it.idx(0).unwrap(), win);
2517 let win: &[_] = &[2,3];
2518 assert_eq!(it.idx(1).unwrap(), win);
2519 let win: &[_] = &[3,4];
2520 assert_eq!(it.idx(2).unwrap(), win);
2521 assert_eq!(it.idx(3), None);
2526 fn test_windowsator_0() {
2528 let _it = v.windows(0);
2532 fn test_chunksator() {
2533 use core::iter::ExactSizeIterator;
2535 let v = &[1,2,3,4,5];
2537 assert_eq!(v.chunks(2).len(), 3);
2539 let chunks: &[&[_]] = &[&[1,2], &[3,4], &[5]];
2540 assert_eq!(v.chunks(2).collect::<Vec<_>>(), chunks);
2541 let chunks: &[&[_]] = &[&[1,2,3], &[4,5]];
2542 assert_eq!(v.chunks(3).collect::<Vec<_>>(), chunks);
2543 let chunks: &[&[_]] = &[&[1,2,3,4,5]];
2544 assert_eq!(v.chunks(6).collect::<Vec<_>>(), chunks);
2546 let chunks: &[&[_]] = &[&[5], &[3,4], &[1,2]];
2547 assert_eq!(v.chunks(2).rev().collect::<Vec<_>>(), chunks);
2548 let mut it = v.chunks(2);
2549 assert_eq!(it.indexable(), 3);
2551 let chunk: &[_] = &[1,2];
2552 assert_eq!(it.idx(0).unwrap(), chunk);
2553 let chunk: &[_] = &[3,4];
2554 assert_eq!(it.idx(1).unwrap(), chunk);
2555 let chunk: &[_] = &[5];
2556 assert_eq!(it.idx(2).unwrap(), chunk);
2557 assert_eq!(it.idx(3), None);
2562 fn test_chunksator_0() {
2564 let _it = v.chunks(0);
2568 fn test_move_from() {
2569 let mut a = [1,2,3,4,5];
2570 let b = vec![6,7,8];
2571 assert_eq!(a.move_from(b, 0, 3), 3);
2572 assert!(a == [6,7,8,4,5]);
2573 let mut a = [7,2,8,1];
2574 let b = vec![3,1,4,1,5,9];
2575 assert_eq!(a.move_from(b, 0, 6), 4);
2576 assert!(a == [3,1,4,1]);
2577 let mut a = [1,2,3,4];
2578 let b = vec![5,6,7,8,9,0];
2579 assert_eq!(a.move_from(b, 2, 3), 1);
2580 assert!(a == [7,2,3,4]);
2581 let mut a = [1,2,3,4,5];
2582 let b = vec![5,6,7,8,9,0];
2583 assert_eq!(a[2..4].move_from(b,1,6), 2);
2584 assert!(a == [1,2,6,7,5]);
2588 fn test_reverse_part() {
2589 let mut values = [1,2,3,4,5];
2590 values[1..4].reverse();
2591 assert!(values == [1,4,3,2,5]);
2596 macro_rules! test_show_vec {
2597 ($x:expr, $x_str:expr) => ({
2598 let (x, x_str) = ($x, $x_str);
2599 assert_eq!(format!("{:?}", x), x_str);
2600 assert_eq!(format!("{:?}", x), x_str);
2603 let empty = Vec::<i32>::new();
2604 test_show_vec!(empty, "[]");
2605 test_show_vec!(vec![1], "[1]");
2606 test_show_vec!(vec![1, 2, 3], "[1, 2, 3]");
2607 test_show_vec!(vec![vec![], vec![1], vec![1, 1]],
2608 "[[], [1], [1, 1]]");
2610 let empty_mut: &mut [i32] = &mut[];
2611 test_show_vec!(empty_mut, "[]");
2613 test_show_vec!(v, "[1]");
2614 let v = &mut[1, 2, 3];
2615 test_show_vec!(v, "[1, 2, 3]");
2616 let v: &mut[&mut[_]] = &mut[&mut[], &mut[1], &mut[1, 1]];
2617 test_show_vec!(v, "[[], [1], [1, 1]]");
2621 fn test_vec_default() {
2624 let v: $ty = Default::default();
2625 assert!(v.is_empty());
2634 fn test_bytes_set_memory() {
2635 use slice::bytes::MutableByteVector;
2636 let mut values = [1u8,2,3,4,5];
2637 values[0..5].set_memory(0xAB);
2638 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
2639 values[2..4].set_memory(0xFF);
2640 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
2645 fn test_overflow_does_not_cause_segfault() {
2647 v.reserve_exact(-1);
2654 fn test_overflow_does_not_cause_segfault_managed() {
2655 let mut v = vec![Rc::new(1)];
2656 v.reserve_exact(-1);
2661 fn test_mut_split_at() {
2662 let mut values = [1u8,2,3,4,5];
2664 let (left, right) = values.split_at_mut(2);
2666 let left: &[_] = left;
2667 assert!(left[..left.len()] == [1, 2][]);
2674 let right: &[_] = right;
2675 assert!(right[..right.len()] == [3, 4, 5][]);
2682 assert!(values == [2, 3, 5, 6, 7]);
2685 #[derive(Clone, PartialEq)]
2689 fn test_iter_zero_sized() {
2690 let mut v = vec![Foo, Foo, Foo];
2691 assert_eq!(v.len(), 3);
2716 assert_eq!(cnt, 11);
2718 let xs: [Foo; 3] = [Foo, Foo, Foo];
2728 fn test_shrink_to_fit() {
2729 let mut xs = vec![0, 1, 2, 3];
2733 assert_eq!(xs.capacity(), 128);
2735 assert_eq!(xs.capacity(), 100);
2736 assert_eq!(xs, (0..100).collect::<Vec<_>>());
2740 fn test_starts_with() {
2741 assert!(b"foobar".starts_with(b"foo"));
2742 assert!(!b"foobar".starts_with(b"oob"));
2743 assert!(!b"foobar".starts_with(b"bar"));
2744 assert!(!b"foo".starts_with(b"foobar"));
2745 assert!(!b"bar".starts_with(b"foobar"));
2746 assert!(b"foobar".starts_with(b"foobar"));
2747 let empty: &[u8] = &[];
2748 assert!(empty.starts_with(empty));
2749 assert!(!empty.starts_with(b"foo"));
2750 assert!(b"foobar".starts_with(empty));
2754 fn test_ends_with() {
2755 assert!(b"foobar".ends_with(b"bar"));
2756 assert!(!b"foobar".ends_with(b"oba"));
2757 assert!(!b"foobar".ends_with(b"foo"));
2758 assert!(!b"foo".ends_with(b"foobar"));
2759 assert!(!b"bar".ends_with(b"foobar"));
2760 assert!(b"foobar".ends_with(b"foobar"));
2761 let empty: &[u8] = &[];
2762 assert!(empty.ends_with(empty));
2763 assert!(!empty.ends_with(b"foo"));
2764 assert!(b"foobar".ends_with(empty));
2768 fn test_mut_splitator() {
2769 let mut xs = [0,1,0,2,3,0,0,4,5,0];
2770 assert_eq!(xs.split_mut(|x| *x == 0).count(), 6);
2771 for slice in xs.split_mut(|x| *x == 0) {
2774 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2776 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
2777 for slice in xs.split_mut(|x| *x == 0).take(5) {
2780 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2784 fn test_mut_splitator_rev() {
2785 let mut xs = [1,2,0,3,4,0,0,5,6,0];
2786 for slice in xs.split_mut(|x| *x == 0).rev().take(4) {
2789 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2794 let mut v = [0,1,2];
2795 assert_eq!(v.get_mut(3), None);
2796 v.get_mut(1).map(|e| *e = 7);
2797 assert_eq!(v[1], 7);
2799 assert_eq!(v.get_mut(2), Some(&mut x));
2803 fn test_mut_chunks() {
2804 use core::iter::ExactSizeIterator;
2806 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2807 assert_eq!(v.chunks_mut(2).len(), 4);
2808 for (i, chunk) in v.chunks_mut(3).enumerate() {
2813 let result = [0u8, 0, 0, 1, 1, 1, 2];
2814 assert!(v == result);
2818 fn test_mut_chunks_rev() {
2819 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2820 for (i, chunk) in v.chunks_mut(3).rev().enumerate() {
2825 let result = [2u8, 2, 2, 1, 1, 1, 0];
2826 assert!(v == result);
2831 fn test_mut_chunks_0() {
2832 let mut v = [1, 2, 3, 4];
2833 let _it = v.chunks_mut(0);
2837 fn test_mut_last() {
2838 let mut x = [1, 2, 3, 4, 5];
2839 let h = x.last_mut();
2840 assert_eq!(*h.unwrap(), 5);
2842 let y: &mut [i32] = &mut [];
2843 assert!(y.last_mut().is_none());
2848 let xs = box [1, 2, 3];
2849 let ys = xs.to_vec();
2850 assert_eq!(ys, [1, 2, 3]);
2859 use core::iter::repeat;
2860 use std::rand::{weak_rng, Rng};
2861 use test::{Bencher, black_box};
2864 fn iterator(b: &mut Bencher) {
2865 // peculiar numbers to stop LLVM from optimising the summation
2867 let v: Vec<_> = (0..100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect();
2874 // sum == 11806, to stop dead code elimination.
2875 if sum == 0 {panic!()}
2880 fn mut_iterator(b: &mut Bencher) {
2881 let mut v: Vec<_> = repeat(0).take(100).collect();
2893 fn concat(b: &mut Bencher) {
2894 let xss: Vec<Vec<i32>> =
2895 (0..100).map(|i| (0..i).collect()).collect();
2902 fn connect(b: &mut Bencher) {
2903 let xss: Vec<Vec<i32>> =
2904 (0..100).map(|i| (0..i).collect()).collect();
2911 fn push(b: &mut Bencher) {
2912 let mut vec = Vec::<i32>::new();
2920 fn starts_with_same_vector(b: &mut Bencher) {
2921 let vec: Vec<_> = (0..100).collect();
2923 vec.starts_with(&vec)
2928 fn starts_with_single_element(b: &mut Bencher) {
2929 let vec: Vec<_> = vec![0];
2931 vec.starts_with(&vec)
2936 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2937 let vec: Vec<_> = (0..100).collect();
2938 let mut match_vec: Vec<_> = (0..99).collect();
2941 vec.starts_with(&match_vec)
2946 fn ends_with_same_vector(b: &mut Bencher) {
2947 let vec: Vec<_> = (0..100).collect();
2954 fn ends_with_single_element(b: &mut Bencher) {
2955 let vec: Vec<_> = vec![0];
2962 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2963 let vec: Vec<_> = (0..100).collect();
2964 let mut match_vec: Vec<_> = (0..100).collect();
2967 vec.starts_with(&match_vec)
2972 fn contains_last_element(b: &mut Bencher) {
2973 let vec: Vec<_> = (0..100).collect();
2980 fn zero_1kb_from_elem(b: &mut Bencher) {
2982 repeat(0u8).take(1024).collect::<Vec<_>>()
2987 fn zero_1kb_set_memory(b: &mut Bencher) {
2989 let mut v = Vec::<u8>::with_capacity(1024);
2991 let vp = v.as_mut_ptr();
2992 ptr::set_memory(vp, 0, 1024);
3000 fn zero_1kb_loop_set(b: &mut Bencher) {
3002 let mut v = Vec::<u8>::with_capacity(1024);
3013 fn zero_1kb_mut_iter(b: &mut Bencher) {
3015 let mut v = Vec::<u8>::with_capacity(1024);
3027 fn random_inserts(b: &mut Bencher) {
3028 let mut rng = weak_rng();
3030 let mut v: Vec<_> = repeat((0, 0)).take(30).collect();
3033 v.insert(rng.gen::<usize>() % (l + 1),
3039 fn random_removes(b: &mut Bencher) {
3040 let mut rng = weak_rng();
3042 let mut v: Vec<_> = repeat((0, 0)).take(130).collect();
3045 v.remove(rng.gen::<usize>() % l);
3051 fn sort_random_small(b: &mut Bencher) {
3052 let mut rng = weak_rng();
3054 let mut v: Vec<_> = rng.gen_iter::<u64>().take(5).collect();
3057 b.bytes = 5 * mem::size_of::<u64>() as u64;
3061 fn sort_random_medium(b: &mut Bencher) {
3062 let mut rng = weak_rng();
3064 let mut v: Vec<_> = rng.gen_iter::<u64>().take(100).collect();
3067 b.bytes = 100 * mem::size_of::<u64>() as u64;
3071 fn sort_random_large(b: &mut Bencher) {
3072 let mut rng = weak_rng();
3074 let mut v: Vec<_> = rng.gen_iter::<u64>().take(10000).collect();
3077 b.bytes = 10000 * mem::size_of::<u64>() as u64;
3081 fn sort_sorted(b: &mut Bencher) {
3082 let mut v: Vec<_> = (0..10000).collect();
3086 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3089 type BigSortable = (u64, u64, u64, u64);
3092 fn sort_big_random_small(b: &mut Bencher) {
3093 let mut rng = weak_rng();
3095 let mut v = rng.gen_iter::<BigSortable>().take(5)
3096 .collect::<Vec<BigSortable>>();
3099 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
3103 fn sort_big_random_medium(b: &mut Bencher) {
3104 let mut rng = weak_rng();
3106 let mut v = rng.gen_iter::<BigSortable>().take(100)
3107 .collect::<Vec<BigSortable>>();
3110 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
3114 fn sort_big_random_large(b: &mut Bencher) {
3115 let mut rng = weak_rng();
3117 let mut v = rng.gen_iter::<BigSortable>().take(10000)
3118 .collect::<Vec<BigSortable>>();
3121 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
3125 fn sort_big_sorted(b: &mut Bencher) {
3126 let mut v: Vec<BigSortable> = (0..10000).map(|i| (i, i, i, i)).collect();
3130 b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;