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[..];
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]`, where `T` represents the element
26 //! type. For example, you can mutate the block of memory that a mutable slice
30 //! let x = &mut [1, 2, 3];
32 //! assert_eq!(x, &[1, 7, 3]);
35 //! Here are some of the things this module contains:
39 //! There are several structs that are useful for slices, such as `Iter`, which
40 //! represents iteration over a slice.
42 //! ## Trait Implementations
44 //! There are several implementations of common traits for slices. Some examples
48 //! * `Eq`, `Ord` - for slices whose element type are `Eq` or `Ord`.
49 //! * `Hash` - for slices whose element type is `Hash`
53 //! The slices implement `IntoIterator`. The iterator yields references to the
57 //! let numbers = &[0, 1, 2];
58 //! for n in numbers {
59 //! println!("{} is a number!", n);
63 //! The mutable slice yields mutable references to the elements:
66 //! let mut scores = [7, 8, 9];
67 //! for score in &mut scores[..] {
72 //! This iterator yields mutable references to the slice's elements, so while the element
73 //! type of the slice is `i32`, the element type of the iterator is `&mut i32`.
75 //! * `.iter()` and `.iter_mut()` are the explicit methods to return the default
77 //! * Further methods that return iterators are `.split()`, `.splitn()`,
78 //! `.chunks()`, `.windows()` and more.
79 #![doc(primitive = "slice")]
80 #![stable(feature = "rust1", since = "1.0.0")]
82 use alloc
::boxed
::Box
;
83 use core
::clone
::Clone
;
84 use core
::cmp
::Ordering
::{self, Greater, Less}
;
85 use core
::cmp
::{self, Ord, PartialEq}
;
86 use core
::iter
::Iterator
;
87 use core
::marker
::Sized
;
88 use core
::mem
::size_of
;
91 use core
::option
::Option
::{self, Some, None}
;
93 use core
::result
::Result
;
94 use core
::slice
as core_slice
;
95 use self::Direction
::*;
97 use borrow
::{Borrow, BorrowMut, ToOwned}
;
100 pub use core
::slice
::{Chunks, Windows}
;
101 pub use core
::slice
::{Iter, IterMut}
;
102 pub use core
::slice
::{IntSliceExt, SplitMut, ChunksMut, Split}
;
103 pub use core
::slice
::{SplitN, RSplitN, SplitNMut, RSplitNMut}
;
104 pub use core
::slice
::{bytes, mut_ref_slice, ref_slice}
;
105 pub use core
::slice
::{from_raw_parts, from_raw_parts_mut}
;
107 ////////////////////////////////////////////////////////////////////////////////
108 // Basic slice extension methods
109 ////////////////////////////////////////////////////////////////////////////////
111 // HACK(japaric) needed for the implementation of `vec!` macro during testing
112 // NB see the hack module in this file for more details
114 pub use self::hack
::into_vec
;
116 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
117 // NB see the hack module in this file for more details
119 pub use self::hack
::to_vec
;
121 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
122 // functions are actually methods that are in `impl [T]` but not in
123 // `core::slice::SliceExt` - we need to supply these functions for the
124 // `test_permutations` test
126 use alloc
::boxed
::Box
;
127 use core
::clone
::Clone
;
129 use core
::iter
::Iterator
;
132 use core
::option
::Option
::{Some, None}
;
135 use string
::ToString
;
138 use super::{ElementSwaps, Permutations}
;
140 pub fn into_vec
<T
>(mut b
: Box
<[T
]>) -> Vec
<T
> {
142 let xs
= Vec
::from_raw_parts(b
.as_mut_ptr(), b
.len(), b
.len());
148 pub fn permutations
<T
>(s
: &[T
]) -> Permutations
<T
> where T
: Clone
{
150 swaps
: ElementSwaps
::new(s
.len()),
156 pub fn to_vec
<T
>(s
: &[T
]) -> Vec
<T
> where T
: Clone
{
157 let mut vector
= Vec
::with_capacity(s
.len());
162 // NB we can remove this hack if we move this test to libcollectionstest -
163 // but that can't be done right now because the test needs access to the
164 // private fields of Permutations
166 fn test_permutations() {
168 let v
: [i32; 0] = [];
169 let mut it
= permutations(&v
);
170 let (min_size
, max_opt
) = it
.size_hint();
171 assert_eq
!(min_size
, 1);
172 assert_eq
!(max_opt
.unwrap(), 1);
173 assert_eq
!(it
.next(), Some(to_vec(&v
)));
174 assert_eq
!(it
.next(), None
);
177 let v
= ["Hello".to_string()];
178 let mut it
= permutations(&v
);
179 let (min_size
, max_opt
) = it
.size_hint();
180 assert_eq
!(min_size
, 1);
181 assert_eq
!(max_opt
.unwrap(), 1);
182 assert_eq
!(it
.next(), Some(to_vec(&v
)));
183 assert_eq
!(it
.next(), None
);
187 let mut it
= permutations(&v
);
188 let (min_size
, max_opt
) = it
.size_hint();
189 assert_eq
!(min_size
, 3*2);
190 assert_eq
!(max_opt
.unwrap(), 3*2);
191 assert_eq
!(it
.next().unwrap(), [1,2,3]);
192 assert_eq
!(it
.next().unwrap(), [1,3,2]);
193 assert_eq
!(it
.next().unwrap(), [3,1,2]);
194 let (min_size
, max_opt
) = it
.size_hint();
195 assert_eq
!(min_size
, 3);
196 assert_eq
!(max_opt
.unwrap(), 3);
197 assert_eq
!(it
.next().unwrap(), [3,2,1]);
198 assert_eq
!(it
.next().unwrap(), [2,3,1]);
199 assert_eq
!(it
.next().unwrap(), [2,1,3]);
200 assert_eq
!(it
.next(), None
);
203 // check that we have N! permutations
204 let v
= ['A'
, 'B'
, 'C'
, 'D'
, 'E'
, 'F'
];
206 let mut it
= permutations(&v
);
207 let (min_size
, max_opt
) = it
.size_hint();
208 for _perm
in it
.by_ref() {
211 assert_eq
!(amt
, it
.swaps
.swaps_made
);
212 assert_eq
!(amt
, min_size
);
213 assert_eq
!(amt
, 2 * 3 * 4 * 5 * 6);
214 assert_eq
!(amt
, max_opt
.unwrap());
219 /// Allocating extension methods for slices.
222 #[stable(feature = "rust1", since = "1.0.0")]
224 /// Sorts the slice, in place, using `compare` to compare
227 /// This sort is `O(n log n)` worst-case and stable, but allocates
228 /// approximately `2 * n`, where `n` is the length of `self`.
233 /// let mut v = [5, 4, 1, 3, 2];
234 /// v.sort_by(|a, b| a.cmp(b));
235 /// assert!(v == [1, 2, 3, 4, 5]);
237 /// // reverse sorting
238 /// v.sort_by(|a, b| b.cmp(a));
239 /// assert!(v == [5, 4, 3, 2, 1]);
241 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn sort_by
<F
>(&mut self, compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
244 merge_sort(self, compare
)
247 /// Consumes `src` and moves as many elements as it can into `self`
248 /// from the range [start,end).
250 /// Returns the number of elements copied (the shorter of `self.len()`
251 /// and `end - start`).
255 /// * src - A mutable vector of `T`
256 /// * start - The index into `src` to start copying from
257 /// * end - The index into `src` to stop copying from
262 /// # #![feature(collections)]
263 /// let mut a = [1, 2, 3, 4, 5];
264 /// let b = vec![6, 7, 8];
265 /// let num_moved = a.move_from(b, 0, 3);
266 /// assert_eq!(num_moved, 3);
267 /// assert!(a == [6, 7, 8, 4, 5]);
269 #[unstable(feature = "collections",
270 reason
= "uncertain about this API approach")]
272 pub fn move_from(&mut self, mut src
: Vec
<T
>, start
: usize, end
: usize) -> usize {
273 for (a
, b
) in self.iter_mut().zip(src
[start
.. end
].iter_mut()) {
276 cmp
::min(self.len(), end
-start
)
279 /// Divides one slice into two at an index.
281 /// The first will contain all indices from `[0, mid)` (excluding
282 /// the index `mid` itself) and the second will contain all
283 /// indices from `[mid, len)` (excluding the index `len` itself).
285 /// Panics if `mid > len`.
290 /// let v = [10, 40, 30, 20, 50];
291 /// let (v1, v2) = v.split_at(2);
292 /// assert_eq!([10, 40], v1);
293 /// assert_eq!([30, 20, 50], v2);
295 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn split_at(&self, mid
: usize) -> (&[T
], &[T
]) {
298 core_slice
::SliceExt
::split_at(self, mid
)
301 /// Returns an iterator over the slice.
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn iter(&self) -> Iter
<T
> {
305 core_slice
::SliceExt
::iter(self)
308 /// Returns an iterator over subslices separated by elements that match
309 /// `pred`. The matched element is not contained in the subslices.
313 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
317 /// let v = [10, 40, 30, 20, 60, 50];
318 /// for group in v.split(|num| *num % 3 == 0) {
319 /// println!("{:?}", group);
322 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn split
<F
>(&self, pred
: F
) -> Split
<T
, F
> where F
: FnMut(&T
) -> bool
{
325 core_slice
::SliceExt
::split(self, pred
)
328 /// Returns an iterator over subslices separated by elements that match
329 /// `pred`, limited to returning at most `n` items. The matched element is
330 /// not contained in the subslices.
332 /// The last element returned, if any, will contain the remainder of the
337 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
341 /// let v = [10, 40, 30, 20, 60, 50];
342 /// for group in v.splitn(2, |num| *num % 3 == 0) {
343 /// println!("{:?}", group);
346 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn splitn
<F
>(&self, n
: usize, pred
: F
) -> SplitN
<T
, F
> where F
: FnMut(&T
) -> bool
{
349 core_slice
::SliceExt
::splitn(self, n
, pred
)
352 /// Returns an iterator over subslices separated by elements that match
353 /// `pred` limited to returning at most `n` items. This starts at the end of
354 /// the slice and works backwards. The matched element is not contained in
357 /// The last element returned, if any, will contain the remainder of the
362 /// Print the slice split once, starting from the end, by numbers divisible
363 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
366 /// let v = [10, 40, 30, 20, 60, 50];
367 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
368 /// println!("{:?}", group);
371 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn rsplitn
<F
>(&self, n
: usize, pred
: F
) -> RSplitN
<T
, F
> where F
: FnMut(&T
) -> bool
{
374 core_slice
::SliceExt
::rsplitn(self, n
, pred
)
377 /// Returns an iterator over all contiguous windows of length
378 /// `size`. The windows overlap. If the slice is shorter than
379 /// `size`, the iterator returns no values.
383 /// Panics if `size` is 0.
387 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
391 /// let v = &[1, 2, 3, 4];
392 /// for win in v.windows(2) {
393 /// println!("{:?}", win);
396 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn windows(&self, size
: usize) -> Windows
<T
> {
399 core_slice
::SliceExt
::windows(self, size
)
402 /// Returns an iterator over `size` elements of the slice at a
403 /// time. The chunks do not overlap. If `size` does not divide the
404 /// length of the slice, then the last chunk will not have length
409 /// Panics if `size` is 0.
413 /// Print the slice two elements at a time (i.e. `[1,2]`,
417 /// let v = &[1, 2, 3, 4, 5];
418 /// for win in v.chunks(2) {
419 /// println!("{:?}", win);
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn chunks(&self, size
: usize) -> Chunks
<T
> {
425 core_slice
::SliceExt
::chunks(self, size
)
428 /// Returns the element of a slice at the given index, or `None` if the
429 /// index is out of bounds.
434 /// let v = [10, 40, 30];
435 /// assert_eq!(Some(&40), v.get(1));
436 /// assert_eq!(None, v.get(3));
438 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn get(&self, index
: usize) -> Option
<&T
> {
441 core_slice
::SliceExt
::get(self, index
)
444 /// Returns the first element of a slice, or `None` if it is empty.
449 /// let v = [10, 40, 30];
450 /// assert_eq!(Some(&10), v.first());
452 /// let w: &[i32] = &[];
453 /// assert_eq!(None, w.first());
455 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn first(&self) -> Option
<&T
> {
458 core_slice
::SliceExt
::first(self)
461 /// Returns all but the first element of a slice.
462 #[unstable(feature = "collections", reason = "likely to be renamed")]
464 pub fn tail(&self) -> &[T
] {
465 core_slice
::SliceExt
::tail(self)
468 /// Returns all but the last element of a slice.
469 #[unstable(feature = "collections", reason = "likely to be renamed")]
471 pub fn init(&self) -> &[T
] {
472 core_slice
::SliceExt
::init(self)
475 /// Returns the last element of a slice, or `None` if it is empty.
480 /// let v = [10, 40, 30];
481 /// assert_eq!(Some(&30), v.last());
483 /// let w: &[i32] = &[];
484 /// assert_eq!(None, w.last());
486 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn last(&self) -> Option
<&T
> {
489 core_slice
::SliceExt
::last(self)
492 /// Returns a pointer to the element at the given index, without doing
494 #[stable(feature = "rust1", since = "1.0.0")]
496 pub unsafe fn get_unchecked(&self, index
: usize) -> &T
{
497 core_slice
::SliceExt
::get_unchecked(self, index
)
500 /// Returns an unsafe pointer to the slice's buffer
502 /// The caller must ensure that the slice outlives the pointer this
503 /// function returns, or else it will end up pointing to garbage.
505 /// Modifying the slice may cause its buffer to be reallocated, which
506 /// would also make any pointers to it invalid.
507 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn as_ptr(&self) -> *const T
{
510 core_slice
::SliceExt
::as_ptr(self)
513 /// Binary search a sorted slice with a comparator function.
515 /// The comparator function should implement an order consistent
516 /// with the sort order of the underlying slice, returning an
517 /// order code that indicates whether its argument is `Less`,
518 /// `Equal` or `Greater` the desired target.
520 /// If a matching value is found then returns `Ok`, containing
521 /// the index for the matched element; if no match is found then
522 /// `Err` is returned, containing the index where a matching
523 /// element could be inserted while maintaining sorted order.
527 /// Looks up a series of four elements. The first is found, with a
528 /// uniquely determined position; the second and third are not
529 /// found; the fourth could match any position in `[1,4]`.
532 /// # #![feature(core)]
533 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
536 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
538 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
540 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
542 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
543 /// assert!(match r { Ok(1...4) => true, _ => false, });
545 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn binary_search_by
<F
>(&self, f
: F
) -> Result
<usize, usize> where F
: FnMut(&T
) -> Ordering
{
548 core_slice
::SliceExt
::binary_search_by(self, f
)
551 /// Returns the number of elements in the slice.
556 /// let a = [1, 2, 3];
557 /// assert_eq!(a.len(), 3);
559 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn len(&self) -> usize {
562 core_slice
::SliceExt
::len(self)
565 /// Returns true if the slice has a length of 0
570 /// let a = [1, 2, 3];
571 /// assert!(!a.is_empty());
573 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn is_empty(&self) -> bool
{
576 core_slice
::SliceExt
::is_empty(self)
579 /// Returns a mutable reference to the element at the given index,
580 /// or `None` if the index is out of bounds
581 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn get_mut(&mut self, index
: usize) -> Option
<&mut T
> {
584 core_slice
::SliceExt
::get_mut(self, index
)
587 /// Returns an iterator that allows modifying each value
588 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn iter_mut(&mut self) -> IterMut
<T
> {
591 core_slice
::SliceExt
::iter_mut(self)
594 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
595 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn first_mut(&mut self) -> Option
<&mut T
> {
598 core_slice
::SliceExt
::first_mut(self)
601 /// Returns all but the first element of a mutable slice
602 #[unstable(feature = "collections",
603 reason
= "likely to be renamed or removed")]
605 pub fn tail_mut(&mut self) -> &mut [T
] {
606 core_slice
::SliceExt
::tail_mut(self)
609 /// Returns all but the last element of a mutable slice
610 #[unstable(feature = "collections",
611 reason
= "likely to be renamed or removed")]
613 pub fn init_mut(&mut self) -> &mut [T
] {
614 core_slice
::SliceExt
::init_mut(self)
617 /// Returns a mutable pointer to the last item in the slice.
618 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn last_mut(&mut self) -> Option
<&mut T
> {
621 core_slice
::SliceExt
::last_mut(self)
624 /// Returns an iterator over mutable subslices separated by elements that
625 /// match `pred`. The matched element is not contained in the subslices.
626 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn split_mut
<F
>(&mut self, pred
: F
) -> SplitMut
<T
, F
> where F
: FnMut(&T
) -> bool
{
629 core_slice
::SliceExt
::split_mut(self, pred
)
632 /// Returns an iterator over subslices separated by elements that match
633 /// `pred`, limited to returning at most `n` items. The matched element is
634 /// not contained in the subslices.
636 /// The last element returned, if any, will contain the remainder of the
638 #[stable(feature = "rust1", since = "1.0.0")]
640 pub fn splitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> SplitNMut
<T
, F
>
641 where F
: FnMut(&T
) -> bool
{
642 core_slice
::SliceExt
::splitn_mut(self, n
, pred
)
645 /// Returns an iterator over subslices separated by elements that match
646 /// `pred` limited to returning at most `n` items. This starts at the end of
647 /// the slice and works backwards. The matched element is not contained in
650 /// The last element returned, if any, will contain the remainder of the
652 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn rsplitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> RSplitNMut
<T
, F
>
655 where F
: FnMut(&T
) -> bool
{
656 core_slice
::SliceExt
::rsplitn_mut(self, n
, pred
)
659 /// Returns an iterator over `chunk_size` elements of the slice at a time.
660 /// The chunks are mutable and do not overlap. If `chunk_size` does
661 /// not divide the length of the slice, then the last chunk will not
662 /// have length `chunk_size`.
666 /// Panics if `chunk_size` is 0.
667 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn chunks_mut(&mut self, chunk_size
: usize) -> ChunksMut
<T
> {
670 core_slice
::SliceExt
::chunks_mut(self, chunk_size
)
673 /// Swaps two elements in a slice.
677 /// * a - The index of the first element
678 /// * b - The index of the second element
682 /// Panics if `a` or `b` are out of bounds.
687 /// let mut v = ["a", "b", "c", "d"];
689 /// assert!(v == ["a", "d", "c", "b"]);
691 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn swap(&mut self, a
: usize, b
: usize) {
694 core_slice
::SliceExt
::swap(self, a
, b
)
697 /// Divides one `&mut` into two at an index.
699 /// The first will contain all indices from `[0, mid)` (excluding
700 /// the index `mid` itself) and the second will contain all
701 /// indices from `[mid, len)` (excluding the index `len` itself).
705 /// Panics if `mid > len`.
710 /// let mut v = [1, 2, 3, 4, 5, 6];
712 /// // scoped to restrict the lifetime of the borrows
714 /// let (left, right) = v.split_at_mut(0);
715 /// assert!(left == []);
716 /// assert!(right == [1, 2, 3, 4, 5, 6]);
720 /// let (left, right) = v.split_at_mut(2);
721 /// assert!(left == [1, 2]);
722 /// assert!(right == [3, 4, 5, 6]);
726 /// let (left, right) = v.split_at_mut(6);
727 /// assert!(left == [1, 2, 3, 4, 5, 6]);
728 /// assert!(right == []);
731 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn split_at_mut(&mut self, mid
: usize) -> (&mut [T
], &mut [T
]) {
734 core_slice
::SliceExt
::split_at_mut(self, mid
)
737 /// Reverse the order of elements in a slice, in place.
742 /// let mut v = [1, 2, 3];
744 /// assert!(v == [3, 2, 1]);
746 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn reverse(&mut self) {
749 core_slice
::SliceExt
::reverse(self)
752 /// Returns an unsafe mutable pointer to the element in index
753 #[stable(feature = "rust1", since = "1.0.0")]
755 pub unsafe fn get_unchecked_mut(&mut self, index
: usize) -> &mut T
{
756 core_slice
::SliceExt
::get_unchecked_mut(self, index
)
759 /// Returns an unsafe mutable pointer to the slice's buffer.
761 /// The caller must ensure that the slice outlives the pointer this
762 /// function returns, or else it will end up pointing to garbage.
764 /// Modifying the slice may cause its buffer to be reallocated, which
765 /// would also make any pointers to it invalid.
766 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn as_mut_ptr(&mut self) -> *mut T
{
769 core_slice
::SliceExt
::as_mut_ptr(self)
772 /// Copies `self` into a new `Vec`.
773 #[stable(feature = "rust1", since = "1.0.0")]
775 pub fn to_vec(&self) -> Vec
<T
> where T
: Clone
{
776 // NB see hack module in this file
780 /// Creates an iterator that yields every possible permutation of the
781 /// vector in succession.
786 /// # #![feature(collections)]
787 /// let v = [1, 2, 3];
788 /// let mut perms = v.permutations();
791 /// println!("{:?}", p);
795 /// Iterating through permutations one by one.
798 /// # #![feature(collections)]
799 /// let v = [1, 2, 3];
800 /// let mut perms = v.permutations();
802 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
803 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
804 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
806 #[unstable(feature = "collections")]
808 pub fn permutations(&self) -> Permutations
<T
> where T
: Clone
{
809 // NB see hack module in this file
810 hack
::permutations(self)
813 /// Copies as many elements from `src` as it can into `self` (the
814 /// shorter of `self.len()` and `src.len()`). Returns the number
815 /// of elements copied.
820 /// # #![feature(collections)]
821 /// let mut dst = [0, 0, 0];
822 /// let src = [1, 2];
824 /// assert!(dst.clone_from_slice(&src) == 2);
825 /// assert!(dst == [1, 2, 0]);
827 /// let src2 = [3, 4, 5, 6];
828 /// assert!(dst.clone_from_slice(&src2) == 3);
829 /// assert!(dst == [3, 4, 5]);
831 #[unstable(feature = "collections")]
832 pub fn clone_from_slice(&mut self, src
: &[T
]) -> usize where T
: Clone
{
833 core_slice
::SliceExt
::clone_from_slice(self, src
)
836 /// Sorts the slice, in place.
838 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
843 /// let mut v = [-5, 4, 1, -3, 2];
846 /// assert!(v == [-5, -3, 1, 2, 4]);
848 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn sort(&mut self) where T
: Ord
{
851 self.sort_by(|a
, b
| a
.cmp(b
))
854 /// Binary search a sorted slice for a given element.
856 /// If the value is found then `Ok` is returned, containing the
857 /// index of the matching element; if the value is not found then
858 /// `Err` is returned, containing the index where a matching
859 /// element could be inserted while maintaining sorted order.
863 /// Looks up a series of four elements. The first is found, with a
864 /// uniquely determined position; the second and third are not
865 /// found; the fourth could match any position in `[1,4]`.
868 /// # #![feature(core)]
869 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
871 /// assert_eq!(s.binary_search(&13), Ok(9));
872 /// assert_eq!(s.binary_search(&4), Err(7));
873 /// assert_eq!(s.binary_search(&100), Err(13));
874 /// let r = s.binary_search(&1);
875 /// assert!(match r { Ok(1...4) => true, _ => false, });
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn binary_search(&self, x
: &T
) -> Result
<usize, usize> where T
: Ord
{
879 core_slice
::SliceExt
::binary_search(self, x
)
882 /// Mutates the slice to the next lexicographic permutation.
884 /// Returns `true` if successful and `false` if the slice is at the
885 /// last-ordered permutation.
890 /// # #![feature(collections)]
891 /// let v: &mut [_] = &mut [0, 1, 2];
892 /// v.next_permutation();
893 /// let b: &mut [_] = &mut [0, 2, 1];
895 /// v.next_permutation();
896 /// let b: &mut [_] = &mut [1, 0, 2];
899 #[unstable(feature = "collections",
900 reason
= "uncertain if this merits inclusion in std")]
901 pub fn next_permutation(&mut self) -> bool
where T
: Ord
{
902 core_slice
::SliceExt
::next_permutation(self)
905 /// Mutates the slice to the previous lexicographic permutation.
907 /// Returns `true` if successful and `false` if the slice is at the
908 /// first-ordered permutation.
913 /// # #![feature(collections)]
914 /// let v: &mut [_] = &mut [1, 0, 2];
915 /// v.prev_permutation();
916 /// let b: &mut [_] = &mut [0, 2, 1];
918 /// v.prev_permutation();
919 /// let b: &mut [_] = &mut [0, 1, 2];
922 #[unstable(feature = "collections",
923 reason
= "uncertain if this merits inclusion in std")]
924 pub fn prev_permutation(&mut self) -> bool
where T
: Ord
{
925 core_slice
::SliceExt
::prev_permutation(self)
928 /// Find the first index containing a matching value.
929 #[unstable(feature = "collections")]
930 pub fn position_elem(&self, t
: &T
) -> Option
<usize> where T
: PartialEq
{
931 core_slice
::SliceExt
::position_elem(self, t
)
934 /// Find the last index containing a matching value.
935 #[unstable(feature = "collections")]
936 pub fn rposition_elem(&self, t
: &T
) -> Option
<usize> where T
: PartialEq
{
937 core_slice
::SliceExt
::rposition_elem(self, t
)
940 /// Returns true if the slice contains an element with the given value.
945 /// let v = [10, 40, 30];
946 /// assert!(v.contains(&30));
947 /// assert!(!v.contains(&50));
949 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn contains(&self, x
: &T
) -> bool
where T
: PartialEq
{
951 core_slice
::SliceExt
::contains(self, x
)
954 /// Returns true if `needle` is a prefix of the slice.
959 /// let v = [10, 40, 30];
960 /// assert!(v.starts_with(&[10]));
961 /// assert!(v.starts_with(&[10, 40]));
962 /// assert!(!v.starts_with(&[50]));
963 /// assert!(!v.starts_with(&[10, 50]));
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn starts_with(&self, needle
: &[T
]) -> bool
where T
: PartialEq
{
967 core_slice
::SliceExt
::starts_with(self, needle
)
970 /// Returns true if `needle` is a suffix of the slice.
975 /// let v = [10, 40, 30];
976 /// assert!(v.ends_with(&[30]));
977 /// assert!(v.ends_with(&[40, 30]));
978 /// assert!(!v.ends_with(&[50]));
979 /// assert!(!v.ends_with(&[50, 30]));
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn ends_with(&self, needle
: &[T
]) -> bool
where T
: PartialEq
{
983 core_slice
::SliceExt
::ends_with(self, needle
)
986 /// Converts `self` into a vector without clones or allocation.
987 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn into_vec(self: Box
<Self>) -> Vec
<T
> {
990 // NB see hack module in this file
995 ////////////////////////////////////////////////////////////////////////////////
996 // Extension traits for slices over specific kinds of data
997 ////////////////////////////////////////////////////////////////////////////////
998 #[unstable(feature = "collections", reason = "recently changed")]
999 /// An extension trait for concatenating slices
1000 pub trait SliceConcatExt
<T
: ?Sized
> {
1001 #[unstable(feature = "collections", reason = "recently changed")]
1002 /// The resulting type after concatenation
1005 /// Flattens a slice of `T` into a single value `Self::Output`.
1010 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 fn concat(&self) -> Self::Output
;
1015 /// Flattens a slice of `T` into a single value `Self::Output`, placing a given separator
1021 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 fn connect(&self, sep
: &T
) -> Self::Output
;
1027 impl<T
: Clone
, V
: Borrow
<[T
]>> SliceConcatExt
<T
> for [V
] {
1028 type Output
= Vec
<T
>;
1030 fn concat(&self) -> Vec
<T
> {
1031 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1032 let mut result
= Vec
::with_capacity(size
);
1034 result
.push_all(v
.borrow())
1039 fn connect(&self, sep
: &T
) -> Vec
<T
> {
1040 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1041 let mut result
= Vec
::with_capacity(size
+ self.len());
1042 let mut first
= true;
1044 if first { first = false }
else { result.push(sep.clone()) }
1045 result
.push_all(v
.borrow())
1051 /// An iterator that yields the element swaps needed to produce
1052 /// a sequence of all possible permutations for an indexed sequence of
1053 /// elements. Each permutation is only a single swap apart.
1055 /// The Steinhaus-Johnson-Trotter algorithm is used.
1057 /// Generates even and odd permutations alternately.
1059 /// The last generated swap is always (0, 1), and it returns the
1060 /// sequence to its initial order.
1061 #[unstable(feature = "collections")]
1063 pub struct ElementSwaps
{
1064 sdir
: Vec
<SizeDirection
>,
1065 /// If `true`, emit the last swap that returns the sequence to initial
1072 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1073 #[unstable(feature = "collections")]
1074 pub fn new(length
: usize) -> ElementSwaps
{
1075 // Initialize `sdir` with a direction that position should move in
1076 // (all negative at the beginning) and the `size` of the
1077 // element (equal to the original index).
1080 sdir
: (0..length
).map(|i
| SizeDirection{ size: i, dir: Neg }
).collect(),
1086 ////////////////////////////////////////////////////////////////////////////////
1087 // Standard trait implementations for slices
1088 ////////////////////////////////////////////////////////////////////////////////
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T
> Borrow
<[T
]> for Vec
<T
> {
1092 fn borrow(&self) -> &[T
] { &self[..] }
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<T
> BorrowMut
<[T
]> for Vec
<T
> {
1097 fn borrow_mut(&mut self) -> &mut [T
] { &mut self[..] }
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<T
: Clone
> ToOwned
for [T
] {
1102 type Owned
= Vec
<T
>;
1104 fn to_owned(&self) -> Vec
<T
> { self.to_vec() }
1106 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1107 // definition, is not available. Since we don't require this method for testing purposes, I'll
1109 // NB see the slice::hack module in slice.rs for more information
1111 fn to_owned(&self) -> Vec
<T
> { panic!("not available with cfg(test)") }
1114 ////////////////////////////////////////////////////////////////////////////////
1116 ////////////////////////////////////////////////////////////////////////////////
1118 #[derive(Copy, Clone)]
1119 enum Direction { Pos, Neg }
1121 /// An `Index` and `Direction` together.
1122 #[derive(Copy, Clone)]
1123 struct SizeDirection
{
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl Iterator
for ElementSwaps
{
1130 type Item
= (usize, usize);
1133 fn next(&mut self) -> Option
<(usize, usize)> {
1134 fn new_pos_wrapping(i
: usize, s
: Direction
) -> usize {
1135 i
.wrapping_add(match s { Pos => 1, Neg => !0 /* aka -1 */ }
)
1138 fn new_pos(i
: usize, s
: Direction
) -> usize {
1139 match s { Pos => i + 1, Neg => i - 1 }
1142 // Find the index of the largest mobile element:
1143 // The direction should point into the vector, and the
1144 // swap should be with a smaller `size` element.
1145 let max
= self.sdir
.iter().cloned().enumerate()
1147 new_pos_wrapping(i
, sd
.dir
) < self.sdir
.len() &&
1148 self.sdir
[new_pos(i
, sd
.dir
)].size
< sd
.size
)
1149 .max_by(|&(_
, sd
)| sd
.size
);
1152 let j
= new_pos(i
, sd
.dir
);
1153 self.sdir
.swap(i
, j
);
1155 // Swap the direction of each larger SizeDirection
1156 for x
in &mut self.sdir
{
1157 if x
.size
> sd
.size
{
1158 x
.dir
= match x
.dir { Pos => Neg, Neg => Pos }
;
1161 self.swaps_made
+= 1;
1164 None
=> if self.emit_reset
{
1165 self.emit_reset
= false;
1166 if self.sdir
.len() > 1 {
1168 self.swaps_made
+= 1;
1171 // Vector is of the form [] or [x], and the only permutation is itself
1172 self.swaps_made
+= 1;
1180 fn size_hint(&self) -> (usize, Option
<usize>) {
1181 // For a vector of size n, there are exactly n! permutations.
1182 let n
: usize = (2..self.sdir
.len() + 1).product();
1183 (n
- self.swaps_made
, Some(n
- self.swaps_made
))
1187 /// An iterator that uses `ElementSwaps` to iterate through
1188 /// all possible permutations of a vector.
1190 /// The first iteration yields a clone of the vector as it is,
1191 /// then each successive element is the vector with one
1194 /// Generates even and odd permutations alternately.
1195 #[unstable(feature = "collections")]
1196 pub struct Permutations
<T
> {
1197 swaps
: ElementSwaps
,
1201 #[unstable(feature = "collections", reason = "trait is unstable")]
1202 impl<T
: Clone
> Iterator
for Permutations
<T
> {
1206 fn next(&mut self) -> Option
<Vec
<T
>> {
1207 match self.swaps
.next() {
1209 Some((0,0)) => Some(self.v
.clone()),
1211 let elt
= self.v
.clone();
1219 fn size_hint(&self) -> (usize, Option
<usize>) {
1220 self.swaps
.size_hint()
1224 ////////////////////////////////////////////////////////////////////////////////
1226 ////////////////////////////////////////////////////////////////////////////////
1228 fn insertion_sort
<T
, F
>(v
: &mut [T
], mut compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
1229 let len
= v
.len() as isize;
1230 let buf_v
= v
.as_mut_ptr();
1234 // j satisfies: 0 <= j <= i;
1237 // `i` is in bounds.
1238 let read_ptr
= buf_v
.offset(i
) as *const T
;
1240 // find where to insert, we need to do strict <,
1241 // rather than <=, to maintain stability.
1243 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1245 compare(&*read_ptr
, &*buf_v
.offset(j
- 1)) == Less
{
1249 // shift everything to the right, to make space to
1250 // insert this value.
1252 // j + 1 could be `len` (for the last `i`), but in
1253 // that case, `i == j` so we don't copy. The
1254 // `.offset(j)` is always in bounds.
1257 let tmp
= ptr
::read(read_ptr
);
1258 ptr
::copy(&*buf_v
.offset(j
),
1259 buf_v
.offset(j
+ 1),
1261 ptr
::copy_nonoverlapping(&tmp
, buf_v
.offset(j
), 1);
1268 fn merge_sort
<T
, F
>(v
: &mut [T
], mut compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
1269 // warning: this wildly uses unsafe.
1270 const BASE_INSERTION
: usize = 32;
1271 const LARGE_INSERTION
: usize = 16;
1273 // FIXME #12092: smaller insertion runs seems to make sorting
1274 // vectors of large elements a little faster on some platforms,
1275 // but hasn't been tested/tuned extensively
1276 let insertion
= if size_of
::<T
>() <= 16 {
1284 // short vectors get sorted in-place via insertion sort to avoid allocations
1285 if len
<= insertion
{
1286 insertion_sort(v
, compare
);
1290 // allocate some memory to use as scratch memory, we keep the
1291 // length 0 so we can keep shallow copies of the contents of `v`
1292 // without risking the dtors running on an object twice if
1293 // `compare` panics.
1294 let mut working_space
= Vec
::with_capacity(2 * len
);
1295 // these both are buffers of length `len`.
1296 let mut buf_dat
= working_space
.as_mut_ptr();
1297 let mut buf_tmp
= unsafe {buf_dat.offset(len as isize)}
;
1300 let buf_v
= v
.as_ptr();
1302 // step 1. sort short runs with insertion sort. This takes the
1303 // values from `v` and sorts them into `buf_dat`, leaving that
1304 // with sorted runs of length INSERTION.
1306 // We could hardcode the sorting comparisons here, and we could
1307 // manipulate/step the pointers themselves, rather than repeatedly
1309 for start
in (0.. len
).step_by(insertion
) {
1310 // start <= i < len;
1311 for i
in start
..cmp
::min(start
+ insertion
, len
) {
1312 // j satisfies: start <= j <= i;
1313 let mut j
= i
as isize;
1315 // `i` is in bounds.
1316 let read_ptr
= buf_v
.offset(i
as isize);
1318 // find where to insert, we need to do strict <,
1319 // rather than <=, to maintain stability.
1321 // start <= j - 1 < len, so .offset(j - 1) is in
1323 while j
> start
as isize &&
1324 compare(&*read_ptr
, &*buf_dat
.offset(j
- 1)) == Less
{
1328 // shift everything to the right, to make space to
1329 // insert this value.
1331 // j + 1 could be `len` (for the last `i`), but in
1332 // that case, `i == j` so we don't copy. The
1333 // `.offset(j)` is always in bounds.
1334 ptr
::copy(&*buf_dat
.offset(j
),
1335 buf_dat
.offset(j
+ 1),
1337 ptr
::copy_nonoverlapping(read_ptr
, buf_dat
.offset(j
), 1);
1342 // step 2. merge the sorted runs.
1343 let mut width
= insertion
;
1345 // merge the sorted runs of length `width` in `buf_dat` two at
1346 // a time, placing the result in `buf_tmp`.
1348 // 0 <= start <= len.
1349 for start
in (0..len
).step_by(2 * width
) {
1350 // manipulate pointers directly for speed (rather than
1351 // using a `for` loop with `range` and `.offset` inside
1354 // the end of the first run & start of the
1355 // second. Offset of `len` is defined, since this is
1356 // precisely one byte past the end of the object.
1357 let right_start
= buf_dat
.offset(cmp
::min(start
+ width
, len
) as isize);
1358 // end of the second. Similar reasoning to the above re safety.
1359 let right_end_idx
= cmp
::min(start
+ 2 * width
, len
);
1360 let right_end
= buf_dat
.offset(right_end_idx
as isize);
1362 // the pointers to the elements under consideration
1363 // from the two runs.
1365 // both of these are in bounds.
1366 let mut left
= buf_dat
.offset(start
as isize);
1367 let mut right
= right_start
;
1369 // where we're putting the results, it is a run of
1370 // length `2*width`, so we step it once for each step
1371 // of either `left` or `right`. `buf_tmp` has length
1372 // `len`, so these are in bounds.
1373 let mut out
= buf_tmp
.offset(start
as isize);
1374 let out_end
= buf_tmp
.offset(right_end_idx
as isize);
1376 while out
< out_end
{
1377 // Either the left or the right run are exhausted,
1378 // so just copy the remainder from the other run
1379 // and move on; this gives a huge speed-up (order
1380 // of 25%) for mostly sorted vectors (the best
1382 if left
== right_start
{
1383 // the number remaining in this run.
1384 let elems
= (right_end
as usize - right
as usize) / mem
::size_of
::<T
>();
1385 ptr
::copy_nonoverlapping(&*right
, out
, elems
);
1387 } else if right
== right_end
{
1388 let elems
= (right_start
as usize - left
as usize) / mem
::size_of
::<T
>();
1389 ptr
::copy_nonoverlapping(&*left
, out
, elems
);
1393 // check which side is smaller, and that's the
1394 // next element for the new run.
1396 // `left < right_start` and `right < right_end`,
1397 // so these are valid.
1398 let to_copy
= if compare(&*left
, &*right
) == Greater
{
1403 ptr
::copy_nonoverlapping(&*to_copy
, out
, 1);
1409 mem
::swap(&mut buf_dat
, &mut buf_tmp
);
1414 // write the result to `v` in one go, so that there are never two copies
1415 // of the same object in `v`.
1417 ptr
::copy_nonoverlapping(&*buf_dat
, v
.as_mut_ptr(), len
);
1420 // increment the pointer, returning the old pointer.
1422 unsafe fn step
<T
>(ptr
: &mut *mut T
) -> *mut T
{
1424 *ptr
= ptr
.offset(1);