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 //! A dynamically-sized view into a contiguous sequence, `[T]`.
13 //! Slices are a view into a block of memory represented as a pointer and a
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
73 //! the element type of the slice is `i32`, the element type of the iterator is
76 //! * `.iter()` and `.iter_mut()` are the explicit methods to return the default
78 //! * Further methods that return iterators are `.split()`, `.splitn()`,
79 //! `.chunks()`, `.windows()` and more.
81 //! *[See also the slice primitive type](../primitive.slice.html).*
82 #![stable(feature = "rust1", since = "1.0.0")]
84 // Many of the usings in this module are only used in the test configuration.
85 // It's cleaner to just turn off the unused_imports warning than to fix them.
86 #![allow(unused_imports)]
88 use alloc
::boxed
::Box
;
89 use core
::clone
::Clone
;
90 use core
::cmp
::Ordering
::{self, Greater, Less}
;
91 use core
::cmp
::{self, Ord, PartialEq}
;
92 use core
::iter
::Iterator
;
93 use core
::marker
::Sized
;
94 use core
::mem
::size_of
;
97 use core
::option
::Option
::{self, Some, None}
;
99 use core
::result
::Result
;
100 use core
::slice
as core_slice
;
101 use self::Direction
::*;
103 use borrow
::{Borrow, BorrowMut, ToOwned}
;
106 pub use core
::slice
::{Chunks, Windows}
;
107 pub use core
::slice
::{Iter, IterMut}
;
108 pub use core
::slice
::{IntSliceExt, SplitMut, ChunksMut, Split}
;
109 pub use core
::slice
::{SplitN, RSplitN, SplitNMut, RSplitNMut}
;
110 pub use core
::slice
::{bytes, mut_ref_slice, ref_slice}
;
111 pub use core
::slice
::{from_raw_parts, from_raw_parts_mut}
;
113 ////////////////////////////////////////////////////////////////////////////////
114 // Basic slice extension methods
115 ////////////////////////////////////////////////////////////////////////////////
117 // HACK(japaric) needed for the implementation of `vec!` macro during testing
118 // NB see the hack module in this file for more details
120 pub use self::hack
::into_vec
;
122 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
123 // NB see the hack module in this file for more details
125 pub use self::hack
::to_vec
;
127 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
128 // functions are actually methods that are in `impl [T]` but not in
129 // `core::slice::SliceExt` - we need to supply these functions for the
130 // `test_permutations` test
132 use alloc
::boxed
::Box
;
133 use core
::clone
::Clone
;
135 use core
::iter
::Iterator
;
138 use core
::option
::Option
::{Some, None}
;
141 use string
::ToString
;
144 use super::{ElementSwaps, Permutations}
;
146 pub fn into_vec
<T
>(mut b
: Box
<[T
]>) -> Vec
<T
> {
148 let xs
= Vec
::from_raw_parts(b
.as_mut_ptr(), b
.len(), b
.len());
155 pub fn permutations
<T
>(s
: &[T
]) -> Permutations
<T
> where T
: Clone
{
157 swaps
: ElementSwaps
::new(s
.len()),
163 pub fn to_vec
<T
>(s
: &[T
]) -> Vec
<T
> where T
: Clone
{
164 let mut vector
= Vec
::with_capacity(s
.len());
169 // NB we can remove this hack if we move this test to libcollectionstest -
170 // but that can't be done right now because the test needs access to the
171 // private fields of Permutations
173 fn test_permutations() {
175 let v
: [i32; 0] = [];
176 let mut it
= permutations(&v
);
177 let (min_size
, max_opt
) = it
.size_hint();
178 assert_eq
!(min_size
, 1);
179 assert_eq
!(max_opt
.unwrap(), 1);
180 assert_eq
!(it
.next(), Some(to_vec(&v
)));
181 assert_eq
!(it
.next(), None
);
184 let v
= ["Hello".to_string()];
185 let mut it
= permutations(&v
);
186 let (min_size
, max_opt
) = it
.size_hint();
187 assert_eq
!(min_size
, 1);
188 assert_eq
!(max_opt
.unwrap(), 1);
189 assert_eq
!(it
.next(), Some(to_vec(&v
)));
190 assert_eq
!(it
.next(), None
);
194 let mut it
= permutations(&v
);
195 let (min_size
, max_opt
) = it
.size_hint();
196 assert_eq
!(min_size
, 3*2);
197 assert_eq
!(max_opt
.unwrap(), 3*2);
198 assert_eq
!(it
.next().unwrap(), [1,2,3]);
199 assert_eq
!(it
.next().unwrap(), [1,3,2]);
200 assert_eq
!(it
.next().unwrap(), [3,1,2]);
201 let (min_size
, max_opt
) = it
.size_hint();
202 assert_eq
!(min_size
, 3);
203 assert_eq
!(max_opt
.unwrap(), 3);
204 assert_eq
!(it
.next().unwrap(), [3,2,1]);
205 assert_eq
!(it
.next().unwrap(), [2,3,1]);
206 assert_eq
!(it
.next().unwrap(), [2,1,3]);
207 assert_eq
!(it
.next(), None
);
210 // check that we have N! permutations
211 let v
= ['A'
, 'B'
, 'C'
, 'D'
, 'E'
, 'F'
];
213 let mut it
= permutations(&v
);
214 let (min_size
, max_opt
) = it
.size_hint();
215 for _perm
in it
.by_ref() {
218 assert_eq
!(amt
, it
.swaps
.swaps_made
);
219 assert_eq
!(amt
, min_size
);
220 assert_eq
!(amt
, 2 * 3 * 4 * 5 * 6);
221 assert_eq
!(amt
, max_opt
.unwrap());
226 /// Allocating extension methods for slices.
229 #[stable(feature = "rust1", since = "1.0.0")]
231 /// Returns the number of elements in the slice.
236 /// let a = [1, 2, 3];
237 /// assert_eq!(a.len(), 3);
239 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn len(&self) -> usize {
242 core_slice
::SliceExt
::len(self)
245 /// Returns true if the slice has a length of 0
250 /// let a = [1, 2, 3];
251 /// assert!(!a.is_empty());
253 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn is_empty(&self) -> bool
{
256 core_slice
::SliceExt
::is_empty(self)
259 /// Returns the first element of a slice, or `None` if it is empty.
264 /// let v = [10, 40, 30];
265 /// assert_eq!(Some(&10), v.first());
267 /// let w: &[i32] = &[];
268 /// assert_eq!(None, w.first());
270 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn first(&self) -> Option
<&T
> {
273 core_slice
::SliceExt
::first(self)
276 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
277 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn first_mut(&mut self) -> Option
<&mut T
> {
280 core_slice
::SliceExt
::first_mut(self)
283 /// Returns all but the first element of a slice.
284 #[unstable(feature = "slice_extras", reason = "likely to be renamed")]
285 #[deprecated(since = "1.3.0", reason = "superseded by split_first")]
287 pub fn tail(&self) -> &[T
] {
288 core_slice
::SliceExt
::tail(self)
291 /// Returns the first and all the rest of the elements of a slice.
292 #[unstable(feature = "slice_splits", reason = "new API")]
294 pub fn split_first(&self) -> Option
<(&T
, &[T
])> {
295 core_slice
::SliceExt
::split_first(self)
298 /// Returns all but the first element of a mutable slice
299 #[unstable(feature = "slice_extras", reason = "likely to be renamed or removed")]
300 #[deprecated(since = "1.3.0", reason = "superseded by split_first_mut")]
302 pub fn tail_mut(&mut self) -> &mut [T
] {
303 core_slice
::SliceExt
::tail_mut(self)
306 /// Returns the first and all the rest of the elements of a slice.
307 #[unstable(feature = "slice_splits", reason = "new API")]
309 pub fn split_first_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
310 core_slice
::SliceExt
::split_first_mut(self)
313 /// Returns all but the last element of a slice.
314 #[unstable(feature = "slice_extras", reason = "likely to be renamed")]
315 #[deprecated(since = "1.3.0", reason = "superseded by split_last")]
317 pub fn init(&self) -> &[T
] {
318 core_slice
::SliceExt
::init(self)
321 /// Returns the last and all the rest of the elements of a slice.
322 #[unstable(feature = "slice_splits", reason = "new API")]
324 pub fn split_last(&self) -> Option
<(&T
, &[T
])> {
325 core_slice
::SliceExt
::split_last(self)
329 /// Returns all but the last element of a mutable slice
330 #[unstable(feature = "slice_extras", reason = "likely to be renamed or removed")]
331 #[deprecated(since = "1.3.0", reason = "superseded by split_last_mut")]
333 pub fn init_mut(&mut self) -> &mut [T
] {
334 core_slice
::SliceExt
::init_mut(self)
337 /// Returns the last and all the rest of the elements of a slice.
338 #[unstable(feature = "slice_splits", since = "1.3.0")]
340 pub fn split_last_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
341 core_slice
::SliceExt
::split_last_mut(self)
344 /// Returns the last element of a slice, or `None` if it is empty.
349 /// let v = [10, 40, 30];
350 /// assert_eq!(Some(&30), v.last());
352 /// let w: &[i32] = &[];
353 /// assert_eq!(None, w.last());
355 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn last(&self) -> Option
<&T
> {
358 core_slice
::SliceExt
::last(self)
361 /// Returns a mutable pointer to the last item in the slice.
362 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn last_mut(&mut self) -> Option
<&mut T
> {
365 core_slice
::SliceExt
::last_mut(self)
368 /// Returns the element of a slice at the given index, or `None` if the
369 /// index is out of bounds.
374 /// let v = [10, 40, 30];
375 /// assert_eq!(Some(&40), v.get(1));
376 /// assert_eq!(None, v.get(3));
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn get(&self, index
: usize) -> Option
<&T
> {
381 core_slice
::SliceExt
::get(self, index
)
384 /// Returns a mutable reference to the element at the given index,
385 /// or `None` if the index is out of bounds
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn get_mut(&mut self, index
: usize) -> Option
<&mut T
> {
389 core_slice
::SliceExt
::get_mut(self, index
)
392 /// Returns a pointer to the element at the given index, without doing
394 #[stable(feature = "rust1", since = "1.0.0")]
396 pub unsafe fn get_unchecked(&self, index
: usize) -> &T
{
397 core_slice
::SliceExt
::get_unchecked(self, index
)
400 /// Returns an unsafe mutable pointer to the element in index
401 #[stable(feature = "rust1", since = "1.0.0")]
403 pub unsafe fn get_unchecked_mut(&mut self, index
: usize) -> &mut T
{
404 core_slice
::SliceExt
::get_unchecked_mut(self, index
)
407 /// Returns an raw pointer to the slice's buffer
409 /// The caller must ensure that the slice outlives the pointer this
410 /// function returns, or else it will end up pointing to garbage.
412 /// Modifying the slice may cause its buffer to be reallocated, which
413 /// would also make any pointers to it invalid.
414 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn as_ptr(&self) -> *const T
{
417 core_slice
::SliceExt
::as_ptr(self)
420 /// Returns an unsafe mutable pointer to the slice's buffer.
422 /// The caller must ensure that the slice outlives the pointer this
423 /// function returns, or else it will end up pointing to garbage.
425 /// Modifying the slice may cause its buffer to be reallocated, which
426 /// would also make any pointers to it invalid.
427 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn as_mut_ptr(&mut self) -> *mut T
{
430 core_slice
::SliceExt
::as_mut_ptr(self)
433 /// Swaps two elements in a slice.
437 /// * a - The index of the first element
438 /// * b - The index of the second element
442 /// Panics if `a` or `b` are out of bounds.
447 /// let mut v = ["a", "b", "c", "d"];
449 /// assert!(v == ["a", "d", "c", "b"]);
451 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn swap(&mut self, a
: usize, b
: usize) {
454 core_slice
::SliceExt
::swap(self, a
, b
)
457 /// Reverse the order of elements in a slice, in place.
462 /// let mut v = [1, 2, 3];
464 /// assert!(v == [3, 2, 1]);
466 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn reverse(&mut self) {
469 core_slice
::SliceExt
::reverse(self)
472 /// Returns an iterator over the slice.
473 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn iter(&self) -> Iter
<T
> {
476 core_slice
::SliceExt
::iter(self)
479 /// Returns an iterator that allows modifying each value
480 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn iter_mut(&mut self) -> IterMut
<T
> {
483 core_slice
::SliceExt
::iter_mut(self)
486 /// Returns an iterator over all contiguous windows of length
487 /// `size`. The windows overlap. If the slice is shorter than
488 /// `size`, the iterator returns no values.
492 /// Panics if `size` is 0.
496 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
500 /// let v = &[1, 2, 3, 4];
501 /// for win in v.windows(2) {
502 /// println!("{:?}", win);
505 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn windows(&self, size
: usize) -> Windows
<T
> {
508 core_slice
::SliceExt
::windows(self, size
)
511 /// Returns an iterator over `size` elements of the slice at a
512 /// time. The chunks do not overlap. If `size` does not divide the
513 /// length of the slice, then the last chunk will not have length
518 /// Panics if `size` is 0.
522 /// Print the slice two elements at a time (i.e. `[1,2]`,
526 /// let v = &[1, 2, 3, 4, 5];
527 /// for win in v.chunks(2) {
528 /// println!("{:?}", win);
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn chunks(&self, size
: usize) -> Chunks
<T
> {
534 core_slice
::SliceExt
::chunks(self, size
)
537 /// Returns an iterator over `chunk_size` elements of the slice at a time.
538 /// The chunks are mutable and do not overlap. If `chunk_size` does
539 /// not divide the length of the slice, then the last chunk will not
540 /// have length `chunk_size`.
544 /// Panics if `chunk_size` is 0.
545 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn chunks_mut(&mut self, chunk_size
: usize) -> ChunksMut
<T
> {
548 core_slice
::SliceExt
::chunks_mut(self, chunk_size
)
551 /// Divides one slice into two at an index.
553 /// The first will contain all indices from `[0, mid)` (excluding
554 /// the index `mid` itself) and the second will contain all
555 /// indices from `[mid, len)` (excluding the index `len` itself).
557 /// Panics if `mid > len`.
562 /// let v = [10, 40, 30, 20, 50];
563 /// let (v1, v2) = v.split_at(2);
564 /// assert_eq!([10, 40], v1);
565 /// assert_eq!([30, 20, 50], v2);
567 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn split_at(&self, mid
: usize) -> (&[T
], &[T
]) {
570 core_slice
::SliceExt
::split_at(self, mid
)
573 /// Divides one `&mut` into two at an index.
575 /// The first will contain all indices from `[0, mid)` (excluding
576 /// the index `mid` itself) and the second will contain all
577 /// indices from `[mid, len)` (excluding the index `len` itself).
581 /// Panics if `mid > len`.
586 /// let mut v = [1, 2, 3, 4, 5, 6];
588 /// // scoped to restrict the lifetime of the borrows
590 /// let (left, right) = v.split_at_mut(0);
591 /// assert!(left == []);
592 /// assert!(right == [1, 2, 3, 4, 5, 6]);
596 /// let (left, right) = v.split_at_mut(2);
597 /// assert!(left == [1, 2]);
598 /// assert!(right == [3, 4, 5, 6]);
602 /// let (left, right) = v.split_at_mut(6);
603 /// assert!(left == [1, 2, 3, 4, 5, 6]);
604 /// assert!(right == []);
607 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn split_at_mut(&mut self, mid
: usize) -> (&mut [T
], &mut [T
]) {
610 core_slice
::SliceExt
::split_at_mut(self, mid
)
613 /// Returns an iterator over subslices separated by elements that match
614 /// `pred`. The matched element is not contained in the subslices.
618 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
622 /// let v = [10, 40, 30, 20, 60, 50];
623 /// for group in v.split(|num| *num % 3 == 0) {
624 /// println!("{:?}", group);
627 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn split
<F
>(&self, pred
: F
) -> Split
<T
, F
> where F
: FnMut(&T
) -> bool
{
630 core_slice
::SliceExt
::split(self, pred
)
633 /// Returns an iterator over mutable subslices separated by elements that
634 /// match `pred`. The matched element is not contained in the subslices.
635 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn split_mut
<F
>(&mut self, pred
: F
) -> SplitMut
<T
, F
> where F
: FnMut(&T
) -> bool
{
638 core_slice
::SliceExt
::split_mut(self, pred
)
641 /// Returns an iterator over subslices separated by elements that match
642 /// `pred`, limited to returning at most `n` items. The matched element is
643 /// not contained in the subslices.
645 /// The last element returned, if any, will contain the remainder of the
650 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
654 /// let v = [10, 40, 30, 20, 60, 50];
655 /// for group in v.splitn(2, |num| *num % 3 == 0) {
656 /// println!("{:?}", group);
659 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn splitn
<F
>(&self, n
: usize, pred
: F
) -> SplitN
<T
, F
> where F
: FnMut(&T
) -> bool
{
662 core_slice
::SliceExt
::splitn(self, n
, pred
)
665 /// Returns an iterator over subslices separated by elements that match
666 /// `pred`, limited to returning at most `n` items. The matched element is
667 /// not contained in the subslices.
669 /// The last element returned, if any, will contain the remainder of the
671 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn splitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> SplitNMut
<T
, F
>
674 where F
: FnMut(&T
) -> bool
{
675 core_slice
::SliceExt
::splitn_mut(self, n
, pred
)
678 /// Returns an iterator over subslices separated by elements that match
679 /// `pred` limited to returning at most `n` items. This starts at the end of
680 /// the slice and works backwards. The matched element is not contained in
683 /// The last element returned, if any, will contain the remainder of the
688 /// Print the slice split once, starting from the end, by numbers divisible
689 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
692 /// let v = [10, 40, 30, 20, 60, 50];
693 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
694 /// println!("{:?}", group);
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn rsplitn
<F
>(&self, n
: usize, pred
: F
) -> RSplitN
<T
, F
> where F
: FnMut(&T
) -> bool
{
700 core_slice
::SliceExt
::rsplitn(self, n
, pred
)
703 /// Returns an iterator over subslices separated by elements that match
704 /// `pred` limited to returning at most `n` items. This starts at the end of
705 /// the slice and works backwards. The matched element is not contained in
708 /// The last element returned, if any, will contain the remainder of the
710 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn rsplitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> RSplitNMut
<T
, F
>
713 where F
: FnMut(&T
) -> bool
{
714 core_slice
::SliceExt
::rsplitn_mut(self, n
, pred
)
717 /// Returns true if the slice contains an element with the given value.
722 /// let v = [10, 40, 30];
723 /// assert!(v.contains(&30));
724 /// assert!(!v.contains(&50));
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn contains(&self, x
: &T
) -> bool
where T
: PartialEq
{
728 core_slice
::SliceExt
::contains(self, x
)
731 /// Returns true if `needle` is a prefix of the slice.
736 /// let v = [10, 40, 30];
737 /// assert!(v.starts_with(&[10]));
738 /// assert!(v.starts_with(&[10, 40]));
739 /// assert!(!v.starts_with(&[50]));
740 /// assert!(!v.starts_with(&[10, 50]));
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn starts_with(&self, needle
: &[T
]) -> bool
where T
: PartialEq
{
744 core_slice
::SliceExt
::starts_with(self, needle
)
747 /// Returns true if `needle` is a suffix of the slice.
752 /// let v = [10, 40, 30];
753 /// assert!(v.ends_with(&[30]));
754 /// assert!(v.ends_with(&[40, 30]));
755 /// assert!(!v.ends_with(&[50]));
756 /// assert!(!v.ends_with(&[50, 30]));
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn ends_with(&self, needle
: &[T
]) -> bool
where T
: PartialEq
{
760 core_slice
::SliceExt
::ends_with(self, needle
)
763 /// Find the first index containing a matching value.
764 #[unstable(feature = "slice_position_elem")]
765 #[deprecated(since = "1.3.0",
766 reason
= "less idiomatic than .iter().position()")]
767 pub fn position_elem(&self, t
: &T
) -> Option
<usize> where T
: PartialEq
{
768 core_slice
::SliceExt
::position_elem(self, t
)
771 /// Find the last index containing a matching value.
772 #[unstable(feature = "slice_position_elem")]
773 #[deprecated(since = "1.3.0",
774 reason
= "less idiomatic than .iter().rev().position()")]
775 pub fn rposition_elem(&self, t
: &T
) -> Option
<usize> where T
: PartialEq
{
776 core_slice
::SliceExt
::rposition_elem(self, t
)
779 /// Binary search a sorted slice for a given element.
781 /// If the value is found then `Ok` is returned, containing the
782 /// index of the matching element; if the value is not found then
783 /// `Err` is returned, containing the index where a matching
784 /// element could be inserted while maintaining sorted order.
788 /// Looks up a series of four elements. The first is found, with a
789 /// uniquely determined position; the second and third are not
790 /// found; the fourth could match any position in `[1,4]`.
793 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
795 /// assert_eq!(s.binary_search(&13), Ok(9));
796 /// assert_eq!(s.binary_search(&4), Err(7));
797 /// assert_eq!(s.binary_search(&100), Err(13));
798 /// let r = s.binary_search(&1);
799 /// assert!(match r { Ok(1...4) => true, _ => false, });
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn binary_search(&self, x
: &T
) -> Result
<usize, usize> where T
: Ord
{
803 core_slice
::SliceExt
::binary_search(self, x
)
806 /// Binary search a sorted slice with a comparator function.
808 /// The comparator function should implement an order consistent
809 /// with the sort order of the underlying slice, returning an
810 /// order code that indicates whether its argument is `Less`,
811 /// `Equal` or `Greater` the desired target.
813 /// If a matching value is found then returns `Ok`, containing
814 /// the index for the matched element; if no match is found then
815 /// `Err` is returned, containing the index where a matching
816 /// element could be inserted while maintaining sorted order.
820 /// Looks up a series of four elements. The first is found, with a
821 /// uniquely determined position; the second and third are not
822 /// found; the fourth could match any position in `[1,4]`.
825 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
828 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
830 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
832 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
834 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
835 /// assert!(match r { Ok(1...4) => true, _ => false, });
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn binary_search_by
<F
>(&self, f
: F
) -> Result
<usize, usize> where F
: FnMut(&T
) -> Ordering
{
840 core_slice
::SliceExt
::binary_search_by(self, f
)
843 /// Sorts the slice, in place.
845 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
850 /// let mut v = [-5, 4, 1, -3, 2];
853 /// assert!(v == [-5, -3, 1, 2, 4]);
855 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn sort(&mut self) where T
: Ord
{
858 self.sort_by(|a
, b
| a
.cmp(b
))
861 /// Sorts the slice, in place, using `compare` to compare
864 /// This sort is `O(n log n)` worst-case and stable, but allocates
865 /// approximately `2 * n`, where `n` is the length of `self`.
870 /// let mut v = [5, 4, 1, 3, 2];
871 /// v.sort_by(|a, b| a.cmp(b));
872 /// assert!(v == [1, 2, 3, 4, 5]);
874 /// // reverse sorting
875 /// v.sort_by(|a, b| b.cmp(a));
876 /// assert!(v == [5, 4, 3, 2, 1]);
878 #[stable(feature = "rust1", since = "1.0.0")]
880 pub fn sort_by
<F
>(&mut self, compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
881 merge_sort(self, compare
)
884 /// Creates an iterator that yields every possible permutation of the
885 /// vector in succession.
890 /// #![feature(permutations)]
892 /// let v = [1, 2, 3];
893 /// let mut perms = v.permutations();
896 /// println!("{:?}", p);
900 /// Iterating through permutations one by one.
903 /// #![feature(permutations)]
905 /// let v = [1, 2, 3];
906 /// let mut perms = v.permutations();
908 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
909 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
910 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
913 #[unstable(feature = "permutations")]
914 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
916 pub fn permutations(&self) -> Permutations
<T
> where T
: Clone
{
917 // NB see hack module in this file
918 hack
::permutations(self)
921 /// Mutates the slice to the next lexicographic permutation.
923 /// Returns `true` if successful and `false` if the slice is at the
924 /// last-ordered permutation.
929 /// #![feature(permutations)]
931 /// let v: &mut [_] = &mut [0, 1, 2];
932 /// v.next_permutation();
933 /// let b: &mut [_] = &mut [0, 2, 1];
935 /// v.next_permutation();
936 /// let b: &mut [_] = &mut [1, 0, 2];
940 #[unstable(feature = "permutations",
941 reason
= "uncertain if this merits inclusion in std")]
942 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
943 pub fn next_permutation(&mut self) -> bool
where T
: Ord
{
944 core_slice
::SliceExt
::next_permutation(self)
947 /// Mutates the slice to the previous lexicographic permutation.
949 /// Returns `true` if successful and `false` if the slice is at the
950 /// first-ordered permutation.
955 /// #![feature(permutations)]
957 /// let v: &mut [_] = &mut [1, 0, 2];
958 /// v.prev_permutation();
959 /// let b: &mut [_] = &mut [0, 2, 1];
961 /// v.prev_permutation();
962 /// let b: &mut [_] = &mut [0, 1, 2];
966 #[unstable(feature = "permutations",
967 reason
= "uncertain if this merits inclusion in std")]
968 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
969 pub fn prev_permutation(&mut self) -> bool
where T
: Ord
{
970 core_slice
::SliceExt
::prev_permutation(self)
973 /// Copies as many elements from `src` as it can into `self` (the
974 /// shorter of `self.len()` and `src.len()`). Returns the number
975 /// of elements copied.
980 /// #![feature(clone_from_slice)]
982 /// let mut dst = [0, 0, 0];
983 /// let src = [1, 2];
985 /// assert!(dst.clone_from_slice(&src) == 2);
986 /// assert!(dst == [1, 2, 0]);
988 /// let src2 = [3, 4, 5, 6];
989 /// assert!(dst.clone_from_slice(&src2) == 3);
990 /// assert!(dst == [3, 4, 5]);
992 #[unstable(feature = "clone_from_slice")]
993 pub fn clone_from_slice(&mut self, src
: &[T
]) -> usize where T
: Clone
{
994 core_slice
::SliceExt
::clone_from_slice(self, src
)
997 /// Consumes `src` and moves as many elements as it can into `self`
998 /// from the range [start,end).
1000 /// Returns the number of elements copied (the shorter of `self.len()`
1001 /// and `end - start`).
1005 /// * src - A mutable vector of `T`
1006 /// * start - The index into `src` to start copying from
1007 /// * end - The index into `src` to stop copying from
1012 /// #![feature(move_from)]
1014 /// let mut a = [1, 2, 3, 4, 5];
1015 /// let b = vec![6, 7, 8];
1016 /// let num_moved = a.move_from(b, 0, 3);
1017 /// assert_eq!(num_moved, 3);
1018 /// assert!(a == [6, 7, 8, 4, 5]);
1020 #[unstable(feature = "move_from",
1021 reason
= "uncertain about this API approach")]
1022 #[deprecated(since = "1.3.0",
1023 reason
= "unclear that it must belong in the standard library")]
1025 pub fn move_from(&mut self, mut src
: Vec
<T
>, start
: usize, end
: usize) -> usize {
1026 for (a
, b
) in self.iter_mut().zip(&mut src
[start
.. end
]) {
1029 cmp
::min(self.len(), end
-start
)
1032 /// Copies `self` into a new `Vec`.
1033 #[stable(feature = "rust1", since = "1.0.0")]
1035 pub fn to_vec(&self) -> Vec
<T
> where T
: Clone
{
1036 // NB see hack module in this file
1040 /// Converts `self` into a vector without clones or allocation.
1041 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn into_vec(self: Box
<Self>) -> Vec
<T
> {
1044 // NB see hack module in this file
1045 hack
::into_vec(self)
1049 ////////////////////////////////////////////////////////////////////////////////
1050 // Extension traits for slices over specific kinds of data
1051 ////////////////////////////////////////////////////////////////////////////////
1052 #[unstable(feature = "slice_concat_ext",
1053 reason
= "trait should not have to exist")]
1054 /// An extension trait for concatenating slices
1055 pub trait SliceConcatExt
<T
: ?Sized
> {
1056 #[unstable(feature = "slice_concat_ext",
1057 reason
= "trait should not have to exist")]
1058 /// The resulting type after concatenation
1061 /// Flattens a slice of `T` into a single value `Self::Output`.
1066 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 fn concat(&self) -> Self::Output
;
1071 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1072 /// given separator between each.
1077 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1079 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1080 fn join(&self, sep
: &T
) -> Self::Output
;
1082 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1083 /// given separator between each.
1088 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 #[deprecated(since = "1.3.0", reason = "renamed to join")]
1092 fn connect(&self, sep
: &T
) -> Self::Output
;
1095 impl<T
: Clone
, V
: Borrow
<[T
]>> SliceConcatExt
<T
> for [V
] {
1096 type Output
= Vec
<T
>;
1098 fn concat(&self) -> Vec
<T
> {
1099 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1100 let mut result
= Vec
::with_capacity(size
);
1102 result
.push_all(v
.borrow())
1107 fn join(&self, sep
: &T
) -> Vec
<T
> {
1108 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1109 let mut result
= Vec
::with_capacity(size
+ self.len());
1110 let mut first
= true;
1112 if first { first = false }
else { result.push(sep.clone()) }
1113 result
.push_all(v
.borrow())
1118 fn connect(&self, sep
: &T
) -> Vec
<T
> {
1123 /// An iterator that yields the element swaps needed to produce
1124 /// a sequence of all possible permutations for an indexed sequence of
1125 /// elements. Each permutation is only a single swap apart.
1127 /// The Steinhaus-Johnson-Trotter algorithm is used.
1129 /// Generates even and odd permutations alternately.
1131 /// The last generated swap is always (0, 1), and it returns the
1132 /// sequence to its initial order.
1133 #[allow(deprecated)]
1134 #[unstable(feature = "permutations")]
1136 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
1137 pub struct ElementSwaps
{
1138 sdir
: Vec
<SizeDirection
>,
1139 /// If `true`, emit the last swap that returns the sequence to initial
1145 #[allow(deprecated)]
1147 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1148 #[unstable(feature = "permutations")]
1149 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
1150 pub fn new(length
: usize) -> ElementSwaps
{
1151 // Initialize `sdir` with a direction that position should move in
1152 // (all negative at the beginning) and the `size` of the
1153 // element (equal to the original index).
1156 sdir
: (0..length
).map(|i
| SizeDirection{ size: i, dir: Neg }
).collect(),
1162 ////////////////////////////////////////////////////////////////////////////////
1163 // Standard trait implementations for slices
1164 ////////////////////////////////////////////////////////////////////////////////
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T
> Borrow
<[T
]> for Vec
<T
> {
1168 fn borrow(&self) -> &[T
] { &self[..] }
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<T
> BorrowMut
<[T
]> for Vec
<T
> {
1173 fn borrow_mut(&mut self) -> &mut [T
] { &mut self[..] }
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T
: Clone
> ToOwned
for [T
] {
1178 type Owned
= Vec
<T
>;
1180 fn to_owned(&self) -> Vec
<T
> { self.to_vec() }
1182 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1183 // definition, is not available. Since we don't require this method for testing purposes, I'll
1185 // NB see the slice::hack module in slice.rs for more information
1187 fn to_owned(&self) -> Vec
<T
> { panic!("not available with cfg(test)") }
1190 ////////////////////////////////////////////////////////////////////////////////
1192 ////////////////////////////////////////////////////////////////////////////////
1194 #[derive(Copy, Clone)]
1195 enum Direction { Pos, Neg }
1197 /// An `Index` and `Direction` together.
1198 #[derive(Copy, Clone)]
1199 struct SizeDirection
{
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 #[allow(deprecated)]
1206 impl Iterator
for ElementSwaps
{
1207 type Item
= (usize, usize);
1210 fn next(&mut self) -> Option
<(usize, usize)> {
1211 fn new_pos_wrapping(i
: usize, s
: Direction
) -> usize {
1212 i
.wrapping_add(match s { Pos => 1, Neg => !0 /* aka -1 */ }
)
1215 fn new_pos(i
: usize, s
: Direction
) -> usize {
1216 match s { Pos => i + 1, Neg => i - 1 }
1219 // Find the index of the largest mobile element:
1220 // The direction should point into the vector, and the
1221 // swap should be with a smaller `size` element.
1222 let max
= self.sdir
.iter().cloned().enumerate()
1224 new_pos_wrapping(i
, sd
.dir
) < self.sdir
.len() &&
1225 self.sdir
[new_pos(i
, sd
.dir
)].size
< sd
.size
)
1226 .max_by(|&(_
, sd
)| sd
.size
);
1229 let j
= new_pos(i
, sd
.dir
);
1230 self.sdir
.swap(i
, j
);
1232 // Swap the direction of each larger SizeDirection
1233 for x
in &mut self.sdir
{
1234 if x
.size
> sd
.size
{
1235 x
.dir
= match x
.dir { Pos => Neg, Neg => Pos }
;
1238 self.swaps_made
+= 1;
1241 None
=> if self.emit_reset
{
1242 self.emit_reset
= false;
1243 if self.sdir
.len() > 1 {
1245 self.swaps_made
+= 1;
1248 // Vector is of the form [] or [x], and the only permutation is itself
1249 self.swaps_made
+= 1;
1257 fn size_hint(&self) -> (usize, Option
<usize>) {
1258 // For a vector of size n, there are exactly n! permutations.
1259 let n
: usize = (2..self.sdir
.len() + 1).product();
1260 (n
- self.swaps_made
, Some(n
- self.swaps_made
))
1264 /// An iterator that uses `ElementSwaps` to iterate through
1265 /// all possible permutations of a vector.
1267 /// The first iteration yields a clone of the vector as it is,
1268 /// then each successive element is the vector with one
1271 /// Generates even and odd permutations alternately.
1272 #[unstable(feature = "permutations")]
1273 #[deprecated(since = "1.2.0", reason = "not clear this should be in the stdlib")]
1274 #[allow(deprecated)]
1275 pub struct Permutations
<T
> {
1276 swaps
: ElementSwaps
,
1280 #[unstable(feature = "permutations", reason = "trait is unstable")]
1281 #[allow(deprecated)]
1282 impl<T
: Clone
> Iterator
for Permutations
<T
> {
1286 fn next(&mut self) -> Option
<Vec
<T
>> {
1287 match self.swaps
.next() {
1289 Some((0,0)) => Some(self.v
.clone()),
1291 let elt
= self.v
.clone();
1299 fn size_hint(&self) -> (usize, Option
<usize>) {
1300 self.swaps
.size_hint()
1304 ////////////////////////////////////////////////////////////////////////////////
1306 ////////////////////////////////////////////////////////////////////////////////
1308 fn insertion_sort
<T
, F
>(v
: &mut [T
], mut compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
1309 let len
= v
.len() as isize;
1310 let buf_v
= v
.as_mut_ptr();
1314 // j satisfies: 0 <= j <= i;
1317 // `i` is in bounds.
1318 let read_ptr
= buf_v
.offset(i
) as *const T
;
1320 // find where to insert, we need to do strict <,
1321 // rather than <=, to maintain stability.
1323 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1325 compare(&*read_ptr
, &*buf_v
.offset(j
- 1)) == Less
{
1329 // shift everything to the right, to make space to
1330 // insert this value.
1332 // j + 1 could be `len` (for the last `i`), but in
1333 // that case, `i == j` so we don't copy. The
1334 // `.offset(j)` is always in bounds.
1337 let tmp
= ptr
::read(read_ptr
);
1338 ptr
::copy(&*buf_v
.offset(j
),
1339 buf_v
.offset(j
+ 1),
1341 ptr
::copy_nonoverlapping(&tmp
, buf_v
.offset(j
), 1);
1348 fn merge_sort
<T
, F
>(v
: &mut [T
], mut compare
: F
) where F
: FnMut(&T
, &T
) -> Ordering
{
1349 // warning: this wildly uses unsafe.
1350 const BASE_INSERTION
: usize = 32;
1351 const LARGE_INSERTION
: usize = 16;
1353 // FIXME #12092: smaller insertion runs seems to make sorting
1354 // vectors of large elements a little faster on some platforms,
1355 // but hasn't been tested/tuned extensively
1356 let insertion
= if size_of
::<T
>() <= 16 {
1364 // short vectors get sorted in-place via insertion sort to avoid allocations
1365 if len
<= insertion
{
1366 insertion_sort(v
, compare
);
1370 // allocate some memory to use as scratch memory, we keep the
1371 // length 0 so we can keep shallow copies of the contents of `v`
1372 // without risking the dtors running on an object twice if
1373 // `compare` panics.
1374 let mut working_space
= Vec
::with_capacity(2 * len
);
1375 // these both are buffers of length `len`.
1376 let mut buf_dat
= working_space
.as_mut_ptr();
1377 let mut buf_tmp
= unsafe {buf_dat.offset(len as isize)}
;
1380 let buf_v
= v
.as_ptr();
1382 // step 1. sort short runs with insertion sort. This takes the
1383 // values from `v` and sorts them into `buf_dat`, leaving that
1384 // with sorted runs of length INSERTION.
1386 // We could hardcode the sorting comparisons here, and we could
1387 // manipulate/step the pointers themselves, rather than repeatedly
1389 for start
in (0.. len
).step_by(insertion
) {
1390 // start <= i < len;
1391 for i
in start
..cmp
::min(start
+ insertion
, len
) {
1392 // j satisfies: start <= j <= i;
1393 let mut j
= i
as isize;
1395 // `i` is in bounds.
1396 let read_ptr
= buf_v
.offset(i
as isize);
1398 // find where to insert, we need to do strict <,
1399 // rather than <=, to maintain stability.
1401 // start <= j - 1 < len, so .offset(j - 1) is in
1403 while j
> start
as isize &&
1404 compare(&*read_ptr
, &*buf_dat
.offset(j
- 1)) == Less
{
1408 // shift everything to the right, to make space to
1409 // insert this value.
1411 // j + 1 could be `len` (for the last `i`), but in
1412 // that case, `i == j` so we don't copy. The
1413 // `.offset(j)` is always in bounds.
1414 ptr
::copy(&*buf_dat
.offset(j
),
1415 buf_dat
.offset(j
+ 1),
1417 ptr
::copy_nonoverlapping(read_ptr
, buf_dat
.offset(j
), 1);
1422 // step 2. merge the sorted runs.
1423 let mut width
= insertion
;
1425 // merge the sorted runs of length `width` in `buf_dat` two at
1426 // a time, placing the result in `buf_tmp`.
1428 // 0 <= start <= len.
1429 for start
in (0..len
).step_by(2 * width
) {
1430 // manipulate pointers directly for speed (rather than
1431 // using a `for` loop with `range` and `.offset` inside
1434 // the end of the first run & start of the
1435 // second. Offset of `len` is defined, since this is
1436 // precisely one byte past the end of the object.
1437 let right_start
= buf_dat
.offset(cmp
::min(start
+ width
, len
) as isize);
1438 // end of the second. Similar reasoning to the above re safety.
1439 let right_end_idx
= cmp
::min(start
+ 2 * width
, len
);
1440 let right_end
= buf_dat
.offset(right_end_idx
as isize);
1442 // the pointers to the elements under consideration
1443 // from the two runs.
1445 // both of these are in bounds.
1446 let mut left
= buf_dat
.offset(start
as isize);
1447 let mut right
= right_start
;
1449 // where we're putting the results, it is a run of
1450 // length `2*width`, so we step it once for each step
1451 // of either `left` or `right`. `buf_tmp` has length
1452 // `len`, so these are in bounds.
1453 let mut out
= buf_tmp
.offset(start
as isize);
1454 let out_end
= buf_tmp
.offset(right_end_idx
as isize);
1456 while out
< out_end
{
1457 // Either the left or the right run are exhausted,
1458 // so just copy the remainder from the other run
1459 // and move on; this gives a huge speed-up (order
1460 // of 25%) for mostly sorted vectors (the best
1462 if left
== right_start
{
1463 // the number remaining in this run.
1464 let elems
= (right_end
as usize - right
as usize) / mem
::size_of
::<T
>();
1465 ptr
::copy_nonoverlapping(&*right
, out
, elems
);
1467 } else if right
== right_end
{
1468 let elems
= (right_start
as usize - left
as usize) / mem
::size_of
::<T
>();
1469 ptr
::copy_nonoverlapping(&*left
, out
, elems
);
1473 // check which side is smaller, and that's the
1474 // next element for the new run.
1476 // `left < right_start` and `right < right_end`,
1477 // so these are valid.
1478 let to_copy
= if compare(&*left
, &*right
) == Greater
{
1483 ptr
::copy_nonoverlapping(&*to_copy
, out
, 1);
1489 mem
::swap(&mut buf_dat
, &mut buf_tmp
);
1494 // write the result to `v` in one go, so that there are never two copies
1495 // of the same object in `v`.
1497 ptr
::copy_nonoverlapping(&*buf_dat
, v
.as_mut_ptr(), len
);
1500 // increment the pointer, returning the old pointer.
1502 unsafe fn step
<T
>(ptr
: &mut *mut T
) -> *mut T
{
1504 *ptr
= ptr
.offset(1);