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](../../std/primitive.slice.html).*
83 //! [`Clone`]: ../../std/clone/trait.Clone.html
84 //! [`Eq`]: ../../std/cmp/trait.Eq.html
85 //! [`Ord`]: ../../std/cmp/trait.Ord.html
86 //! [`Iter`]: struct.Iter.html
87 //! [`Hash`]: ../../std/hash/trait.Hash.html
88 //! [`.iter()`]: ../../std/primitive.slice.html#method.iter
89 //! [`.iter_mut()`]: ../../std/primitive.slice.html#method.iter_mut
90 //! [`.split()`]: ../../std/primitive.slice.html#method.split
91 //! [`.splitn()`]: ../../std/primitive.slice.html#method.splitn
92 //! [`.chunks()`]: ../../std/primitive.slice.html#method.chunks
93 //! [`.windows()`]: ../../std/primitive.slice.html#method.windows
94 #![stable(feature = "rust1", since = "1.0.0")]
96 // Many of the usings in this module are only used in the test configuration.
97 // It's cleaner to just turn off the unused_imports warning than to fix them.
98 #![cfg_attr(test, allow(unused_imports, dead_code))]
100 use alloc
::boxed
::Box
;
101 use core
::cmp
::Ordering
::{self, Less}
;
102 use core
::mem
::size_of
;
105 use core
::slice
as core_slice
;
107 use borrow
::{Borrow, BorrowMut, ToOwned}
;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub use core
::slice
::{Chunks, Windows}
;
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub use core
::slice
::{Iter, IterMut}
;
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub use core
::slice
::{SplitMut, ChunksMut, Split}
;
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub use core
::slice
::{SplitN, RSplitN, SplitNMut, RSplitNMut}
;
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub use core
::slice
::{from_raw_parts, from_raw_parts_mut}
;
120 #[unstable(feature = "slice_get_slice", issue = "35729")]
121 pub use core
::slice
::SliceIndex
;
123 ////////////////////////////////////////////////////////////////////////////////
124 // Basic slice extension methods
125 ////////////////////////////////////////////////////////////////////////////////
127 // HACK(japaric) needed for the implementation of `vec!` macro during testing
128 // NB see the hack module in this file for more details
130 pub use self::hack
::into_vec
;
132 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
133 // NB see the hack module in this file for more details
135 pub use self::hack
::to_vec
;
137 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
138 // functions are actually methods that are in `impl [T]` but not in
139 // `core::slice::SliceExt` - we need to supply these functions for the
140 // `test_permutations` test
142 use alloc
::boxed
::Box
;
146 use string
::ToString
;
149 pub fn into_vec
<T
>(mut b
: Box
<[T
]>) -> Vec
<T
> {
151 let xs
= Vec
::from_raw_parts(b
.as_mut_ptr(), b
.len(), b
.len());
158 pub fn to_vec
<T
>(s
: &[T
]) -> Vec
<T
>
161 let mut vector
= Vec
::with_capacity(s
.len());
162 vector
.extend_from_slice(s
);
170 /// Returns the number of elements in the slice.
175 /// let a = [1, 2, 3];
176 /// assert_eq!(a.len(), 3);
178 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn len(&self) -> usize {
181 core_slice
::SliceExt
::len(self)
184 /// Returns `true` if the slice has a length of 0.
189 /// let a = [1, 2, 3];
190 /// assert!(!a.is_empty());
192 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn is_empty(&self) -> bool
{
195 core_slice
::SliceExt
::is_empty(self)
198 /// Returns the first element of a slice, or `None` if it is empty.
203 /// let v = [10, 40, 30];
204 /// assert_eq!(Some(&10), v.first());
206 /// let w: &[i32] = &[];
207 /// assert_eq!(None, w.first());
209 #[stable(feature = "rust1", since = "1.0.0")]
211 pub fn first(&self) -> Option
<&T
> {
212 core_slice
::SliceExt
::first(self)
215 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty.
220 /// let x = &mut [0, 1, 2];
222 /// if let Some(first) = x.first_mut() {
225 /// assert_eq!(x, &[5, 1, 2]);
227 #[stable(feature = "rust1", since = "1.0.0")]
229 pub fn first_mut(&mut self) -> Option
<&mut T
> {
230 core_slice
::SliceExt
::first_mut(self)
233 /// Returns the first and all the rest of the elements of a slice.
238 /// let x = &[0, 1, 2];
240 /// if let Some((first, elements)) = x.split_first() {
241 /// assert_eq!(first, &0);
242 /// assert_eq!(elements, &[1, 2]);
245 #[stable(feature = "slice_splits", since = "1.5.0")]
247 pub fn split_first(&self) -> Option
<(&T
, &[T
])> {
248 core_slice
::SliceExt
::split_first(self)
251 /// Returns the first and all the rest of the elements of a slice.
256 /// let x = &mut [0, 1, 2];
258 /// if let Some((first, elements)) = x.split_first_mut() {
263 /// assert_eq!(x, &[3, 4, 5]);
265 #[stable(feature = "slice_splits", since = "1.5.0")]
267 pub fn split_first_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
268 core_slice
::SliceExt
::split_first_mut(self)
271 /// Returns the last and all the rest of the elements of a slice.
276 /// let x = &[0, 1, 2];
278 /// if let Some((last, elements)) = x.split_last() {
279 /// assert_eq!(last, &2);
280 /// assert_eq!(elements, &[0, 1]);
283 #[stable(feature = "slice_splits", since = "1.5.0")]
285 pub fn split_last(&self) -> Option
<(&T
, &[T
])> {
286 core_slice
::SliceExt
::split_last(self)
290 /// Returns the last and all the rest of the elements of a slice.
295 /// let x = &mut [0, 1, 2];
297 /// if let Some((last, elements)) = x.split_last_mut() {
302 /// assert_eq!(x, &[4, 5, 3]);
304 #[stable(feature = "slice_splits", since = "1.5.0")]
306 pub fn split_last_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
307 core_slice
::SliceExt
::split_last_mut(self)
310 /// Returns the last element of a slice, or `None` if it is empty.
315 /// let v = [10, 40, 30];
316 /// assert_eq!(Some(&30), v.last());
318 /// let w: &[i32] = &[];
319 /// assert_eq!(None, w.last());
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn last(&self) -> Option
<&T
> {
324 core_slice
::SliceExt
::last(self)
327 /// Returns a mutable pointer to the last item in the slice.
332 /// let x = &mut [0, 1, 2];
334 /// if let Some(last) = x.last_mut() {
337 /// assert_eq!(x, &[0, 1, 10]);
339 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn last_mut(&mut self) -> Option
<&mut T
> {
342 core_slice
::SliceExt
::last_mut(self)
345 /// Returns a reference to an element or subslice depending on the type of
348 /// - If given a position, returns a reference to the element at that
349 /// position or `None` if out of bounds.
350 /// - If given a range, returns the subslice corresponding to that range,
351 /// or `None` if out of bounds.
356 /// let v = [10, 40, 30];
357 /// assert_eq!(Some(&40), v.get(1));
358 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
359 /// assert_eq!(None, v.get(3));
360 /// assert_eq!(None, v.get(0..4));
362 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn get
<I
>(&self, index
: I
) -> Option
<&I
::Output
>
365 where I
: SliceIndex
<T
>
367 core_slice
::SliceExt
::get(self, index
)
370 /// Returns a mutable reference to an element or subslice depending on the
371 /// type of index (see [`get()`]) or `None` if the index is out of bounds.
373 /// [`get()`]: #method.get
378 /// let x = &mut [0, 1, 2];
380 /// if let Some(elem) = x.get_mut(1) {
383 /// assert_eq!(x, &[0, 42, 2]);
385 #[stable(feature = "rust1", since = "1.0.0")]
387 pub fn get_mut
<I
>(&mut self, index
: I
) -> Option
<&mut I
::Output
>
388 where I
: SliceIndex
<T
>
390 core_slice
::SliceExt
::get_mut(self, index
)
393 /// Returns a reference to an element or subslice, without doing bounds
394 /// checking. So use it very carefully!
399 /// let x = &[1, 2, 4];
402 /// assert_eq!(x.get_unchecked(1), &2);
405 #[stable(feature = "rust1", since = "1.0.0")]
407 pub unsafe fn get_unchecked
<I
>(&self, index
: I
) -> &I
::Output
408 where I
: SliceIndex
<T
>
410 core_slice
::SliceExt
::get_unchecked(self, index
)
413 /// Returns a mutable reference to an element or subslice, without doing
414 /// bounds checking. So use it very carefully!
419 /// let x = &mut [1, 2, 4];
422 /// let elem = x.get_unchecked_mut(1);
425 /// assert_eq!(x, &[1, 13, 4]);
427 #[stable(feature = "rust1", since = "1.0.0")]
429 pub unsafe fn get_unchecked_mut
<I
>(&mut self, index
: I
) -> &mut I
::Output
430 where I
: SliceIndex
<T
>
432 core_slice
::SliceExt
::get_unchecked_mut(self, index
)
435 /// Returns a raw pointer to the slice's buffer.
437 /// The caller must ensure that the slice outlives the pointer this
438 /// function returns, or else it will end up pointing to garbage.
440 /// Modifying the slice may cause its buffer to be reallocated, which
441 /// would also make any pointers to it invalid.
446 /// let x = &[1, 2, 4];
447 /// let x_ptr = x.as_ptr();
450 /// for i in 0..x.len() {
451 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
455 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn as_ptr(&self) -> *const T
{
458 core_slice
::SliceExt
::as_ptr(self)
461 /// Returns an unsafe mutable pointer to the slice's buffer.
463 /// The caller must ensure that the slice outlives the pointer this
464 /// function returns, or else it will end up pointing to garbage.
466 /// Modifying the slice may cause its buffer to be reallocated, which
467 /// would also make any pointers to it invalid.
472 /// let x = &mut [1, 2, 4];
473 /// let x_ptr = x.as_mut_ptr();
476 /// for i in 0..x.len() {
477 /// *x_ptr.offset(i as isize) += 2;
480 /// assert_eq!(x, &[3, 4, 6]);
482 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn as_mut_ptr(&mut self) -> *mut T
{
485 core_slice
::SliceExt
::as_mut_ptr(self)
488 /// Swaps two elements in a slice.
492 /// * a - The index of the first element
493 /// * b - The index of the second element
497 /// Panics if `a` or `b` are out of bounds.
502 /// let mut v = ["a", "b", "c", "d"];
504 /// assert!(v == ["a", "d", "c", "b"]);
506 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn swap(&mut self, a
: usize, b
: usize) {
509 core_slice
::SliceExt
::swap(self, a
, b
)
512 /// Reverses the order of elements in a slice, in place.
517 /// let mut v = [1, 2, 3];
519 /// assert!(v == [3, 2, 1]);
521 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn reverse(&mut self) {
524 core_slice
::SliceExt
::reverse(self)
527 /// Returns an iterator over the slice.
532 /// let x = &[1, 2, 4];
533 /// let mut iterator = x.iter();
535 /// assert_eq!(iterator.next(), Some(&1));
536 /// assert_eq!(iterator.next(), Some(&2));
537 /// assert_eq!(iterator.next(), Some(&4));
538 /// assert_eq!(iterator.next(), None);
540 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn iter(&self) -> Iter
<T
> {
543 core_slice
::SliceExt
::iter(self)
546 /// Returns an iterator that allows modifying each value.
551 /// let x = &mut [1, 2, 4];
552 /// for elem in x.iter_mut() {
555 /// assert_eq!(x, &[3, 4, 6]);
557 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn iter_mut(&mut self) -> IterMut
<T
> {
560 core_slice
::SliceExt
::iter_mut(self)
563 /// Returns an iterator over all contiguous windows of length
564 /// `size`. The windows overlap. If the slice is shorter than
565 /// `size`, the iterator returns no values.
569 /// Panics if `size` is 0.
574 /// let slice = ['r', 'u', 's', 't'];
575 /// let mut iter = slice.windows(2);
576 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
577 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
578 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
579 /// assert!(iter.next().is_none());
582 /// If the slice is shorter than `size`:
585 /// let slice = ['f', 'o', 'o'];
586 /// let mut iter = slice.windows(4);
587 /// assert!(iter.next().is_none());
589 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn windows(&self, size
: usize) -> Windows
<T
> {
592 core_slice
::SliceExt
::windows(self, size
)
595 /// Returns an iterator over `size` elements of the slice at a
596 /// time. The chunks are slices and do not overlap. If `size` does
597 /// not divide the length of the slice, then the last chunk will
598 /// not have length `size`.
602 /// Panics if `size` is 0.
607 /// let slice = ['l', 'o', 'r', 'e', 'm'];
608 /// let mut iter = slice.chunks(2);
609 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
610 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
611 /// assert_eq!(iter.next().unwrap(), &['m']);
612 /// assert!(iter.next().is_none());
614 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn chunks(&self, size
: usize) -> Chunks
<T
> {
617 core_slice
::SliceExt
::chunks(self, size
)
620 /// Returns an iterator over `chunk_size` elements of the slice at a time.
621 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
622 /// not divide the length of the slice, then the last chunk will not
623 /// have length `chunk_size`.
627 /// Panics if `chunk_size` is 0.
632 /// let v = &mut [0, 0, 0, 0, 0];
633 /// let mut count = 1;
635 /// for chunk in v.chunks_mut(2) {
636 /// for elem in chunk.iter_mut() {
641 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
643 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn chunks_mut(&mut self, chunk_size
: usize) -> ChunksMut
<T
> {
646 core_slice
::SliceExt
::chunks_mut(self, chunk_size
)
649 /// Divides one slice into two at an index.
651 /// The first will contain all indices from `[0, mid)` (excluding
652 /// the index `mid` itself) and the second will contain all
653 /// indices from `[mid, len)` (excluding the index `len` itself).
657 /// Panics if `mid > len`.
662 /// let v = [10, 40, 30, 20, 50];
663 /// let (v1, v2) = v.split_at(2);
664 /// assert_eq!([10, 40], v1);
665 /// assert_eq!([30, 20, 50], v2);
667 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn split_at(&self, mid
: usize) -> (&[T
], &[T
]) {
670 core_slice
::SliceExt
::split_at(self, mid
)
673 /// Divides one `&mut` into two at an index.
675 /// The first will contain all indices from `[0, mid)` (excluding
676 /// the index `mid` itself) and the second will contain all
677 /// indices from `[mid, len)` (excluding the index `len` itself).
681 /// Panics if `mid > len`.
686 /// let mut v = [1, 2, 3, 4, 5, 6];
688 /// // scoped to restrict the lifetime of the borrows
690 /// let (left, right) = v.split_at_mut(0);
691 /// assert!(left == []);
692 /// assert!(right == [1, 2, 3, 4, 5, 6]);
696 /// let (left, right) = v.split_at_mut(2);
697 /// assert!(left == [1, 2]);
698 /// assert!(right == [3, 4, 5, 6]);
702 /// let (left, right) = v.split_at_mut(6);
703 /// assert!(left == [1, 2, 3, 4, 5, 6]);
704 /// assert!(right == []);
707 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn split_at_mut(&mut self, mid
: usize) -> (&mut [T
], &mut [T
]) {
710 core_slice
::SliceExt
::split_at_mut(self, mid
)
713 /// Returns an iterator over subslices separated by elements that match
714 /// `pred`. The matched element is not contained in the subslices.
719 /// let slice = [10, 40, 33, 20];
720 /// let mut iter = slice.split(|num| num % 3 == 0);
722 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
723 /// assert_eq!(iter.next().unwrap(), &[20]);
724 /// assert!(iter.next().is_none());
727 /// If the first element is matched, an empty slice will be the first item
728 /// returned by the iterator. Similarly, if the last element in the slice
729 /// is matched, an empty slice will be the last item returned by the
733 /// let slice = [10, 40, 33];
734 /// let mut iter = slice.split(|num| num % 3 == 0);
736 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
737 /// assert_eq!(iter.next().unwrap(), &[]);
738 /// assert!(iter.next().is_none());
741 /// If two matched elements are directly adjacent, an empty slice will be
742 /// present between them:
745 /// let slice = [10, 6, 33, 20];
746 /// let mut iter = slice.split(|num| num % 3 == 0);
748 /// assert_eq!(iter.next().unwrap(), &[10]);
749 /// assert_eq!(iter.next().unwrap(), &[]);
750 /// assert_eq!(iter.next().unwrap(), &[20]);
751 /// assert!(iter.next().is_none());
753 #[stable(feature = "rust1", since = "1.0.0")]
755 pub fn split
<F
>(&self, pred
: F
) -> Split
<T
, F
>
756 where F
: FnMut(&T
) -> bool
758 core_slice
::SliceExt
::split(self, pred
)
761 /// Returns an iterator over mutable subslices separated by elements that
762 /// match `pred`. The matched element is not contained in the subslices.
767 /// let mut v = [10, 40, 30, 20, 60, 50];
769 /// for group in v.split_mut(|num| *num % 3 == 0) {
772 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
774 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn split_mut
<F
>(&mut self, pred
: F
) -> SplitMut
<T
, F
>
777 where F
: FnMut(&T
) -> bool
779 core_slice
::SliceExt
::split_mut(self, pred
)
782 /// Returns an iterator over subslices separated by elements that match
783 /// `pred`, limited to returning at most `n` items. The matched element is
784 /// not contained in the subslices.
786 /// The last element returned, if any, will contain the remainder of the
791 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
795 /// let v = [10, 40, 30, 20, 60, 50];
797 /// for group in v.splitn(2, |num| *num % 3 == 0) {
798 /// println!("{:?}", group);
801 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn splitn
<F
>(&self, n
: usize, pred
: F
) -> SplitN
<T
, F
>
804 where F
: FnMut(&T
) -> bool
806 core_slice
::SliceExt
::splitn(self, n
, pred
)
809 /// Returns an iterator over subslices separated by elements that match
810 /// `pred`, limited to returning at most `n` items. The matched element is
811 /// not contained in the subslices.
813 /// The last element returned, if any, will contain the remainder of the
819 /// let mut v = [10, 40, 30, 20, 60, 50];
821 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
824 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
826 #[stable(feature = "rust1", since = "1.0.0")]
828 pub fn splitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> SplitNMut
<T
, F
>
829 where F
: FnMut(&T
) -> bool
831 core_slice
::SliceExt
::splitn_mut(self, n
, pred
)
834 /// Returns an iterator over subslices separated by elements that match
835 /// `pred` limited to returning at most `n` items. This starts at the end of
836 /// the slice and works backwards. The matched element is not contained in
839 /// The last element returned, if any, will contain the remainder of the
844 /// Print the slice split once, starting from the end, by numbers divisible
845 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
848 /// let v = [10, 40, 30, 20, 60, 50];
850 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
851 /// println!("{:?}", group);
854 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn rsplitn
<F
>(&self, n
: usize, pred
: F
) -> RSplitN
<T
, F
>
857 where F
: FnMut(&T
) -> bool
859 core_slice
::SliceExt
::rsplitn(self, n
, pred
)
862 /// Returns an iterator over subslices separated by elements that match
863 /// `pred` limited to returning at most `n` items. This starts at the end of
864 /// the slice and works backwards. The matched element is not contained in
867 /// The last element returned, if any, will contain the remainder of the
873 /// let mut s = [10, 40, 30, 20, 60, 50];
875 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
878 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
880 #[stable(feature = "rust1", since = "1.0.0")]
882 pub fn rsplitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> RSplitNMut
<T
, F
>
883 where F
: FnMut(&T
) -> bool
885 core_slice
::SliceExt
::rsplitn_mut(self, n
, pred
)
888 /// Returns `true` if the slice contains an element with the given value.
893 /// let v = [10, 40, 30];
894 /// assert!(v.contains(&30));
895 /// assert!(!v.contains(&50));
897 #[stable(feature = "rust1", since = "1.0.0")]
898 pub fn contains(&self, x
: &T
) -> bool
901 core_slice
::SliceExt
::contains(self, x
)
904 /// Returns `true` if `needle` is a prefix of the slice.
909 /// let v = [10, 40, 30];
910 /// assert!(v.starts_with(&[10]));
911 /// assert!(v.starts_with(&[10, 40]));
912 /// assert!(!v.starts_with(&[50]));
913 /// assert!(!v.starts_with(&[10, 50]));
916 /// Always returns `true` if `needle` is an empty slice:
919 /// let v = &[10, 40, 30];
920 /// assert!(v.starts_with(&[]));
921 /// let v: &[u8] = &[];
922 /// assert!(v.starts_with(&[]));
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub fn starts_with(&self, needle
: &[T
]) -> bool
928 core_slice
::SliceExt
::starts_with(self, needle
)
931 /// Returns `true` if `needle` is a suffix of the slice.
936 /// let v = [10, 40, 30];
937 /// assert!(v.ends_with(&[30]));
938 /// assert!(v.ends_with(&[40, 30]));
939 /// assert!(!v.ends_with(&[50]));
940 /// assert!(!v.ends_with(&[50, 30]));
943 /// Always returns `true` if `needle` is an empty slice:
946 /// let v = &[10, 40, 30];
947 /// assert!(v.ends_with(&[]));
948 /// let v: &[u8] = &[];
949 /// assert!(v.ends_with(&[]));
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn ends_with(&self, needle
: &[T
]) -> bool
955 core_slice
::SliceExt
::ends_with(self, needle
)
958 /// Binary search a sorted slice for a given element.
960 /// If the value is found then `Ok` is returned, containing the
961 /// index of the matching element; if the value is not found then
962 /// `Err` is returned, containing the index where a matching
963 /// element could be inserted while maintaining sorted order.
967 /// Looks up a series of four elements. The first is found, with a
968 /// uniquely determined position; the second and third are not
969 /// found; the fourth could match any position in `[1, 4]`.
972 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
974 /// assert_eq!(s.binary_search(&13), Ok(9));
975 /// assert_eq!(s.binary_search(&4), Err(7));
976 /// assert_eq!(s.binary_search(&100), Err(13));
977 /// let r = s.binary_search(&1);
978 /// assert!(match r { Ok(1...4) => true, _ => false, });
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn binary_search(&self, x
: &T
) -> Result
<usize, usize>
984 core_slice
::SliceExt
::binary_search(self, x
)
987 /// Binary search a sorted slice with a comparator function.
989 /// The comparator function should implement an order consistent
990 /// with the sort order of the underlying slice, returning an
991 /// order code that indicates whether its argument is `Less`,
992 /// `Equal` or `Greater` the desired target.
994 /// If a matching value is found then returns `Ok`, containing
995 /// the index for the matched element; if no match is found then
996 /// `Err` is returned, containing the index where a matching
997 /// element could be inserted while maintaining sorted order.
1001 /// Looks up a series of four elements. The first is found, with a
1002 /// uniquely determined position; the second and third are not
1003 /// found; the fourth could match any position in `[1, 4]`.
1006 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1009 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1011 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1013 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1015 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1016 /// assert!(match r { Ok(1...4) => true, _ => false, });
1018 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn binary_search_by
<'a
, F
>(&'a
self, f
: F
) -> Result
<usize, usize>
1021 where F
: FnMut(&'a T
) -> Ordering
1023 core_slice
::SliceExt
::binary_search_by(self, f
)
1026 /// Binary search a sorted slice with a key extraction function.
1028 /// Assumes that the slice is sorted by the key, for instance with
1029 /// [`sort_by_key`] using the same key extraction function.
1031 /// If a matching value is found then returns `Ok`, containing the
1032 /// index for the matched element; if no match is found then `Err`
1033 /// is returned, containing the index where a matching element could
1034 /// be inserted while maintaining sorted order.
1036 /// [`sort_by_key`]: #method.sort_by_key
1040 /// Looks up a series of four elements in a slice of pairs sorted by
1041 /// their second elements. The first is found, with a uniquely
1042 /// determined position; the second and third are not found; the
1043 /// fourth could match any position in `[1, 4]`.
1046 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1047 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1048 /// (1, 21), (2, 34), (4, 55)];
1050 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1051 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1052 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1053 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1054 /// assert!(match r { Ok(1...4) => true, _ => false, });
1056 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1058 pub fn binary_search_by_key
<'a
, B
, F
>(&'a
self, b
: &B
, f
: F
) -> Result
<usize, usize>
1059 where F
: FnMut(&'a T
) -> B
,
1062 core_slice
::SliceExt
::binary_search_by_key(self, b
, f
)
1065 /// Sorts the slice.
1067 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1069 /// # Current implementation
1071 /// The current algorithm is an adaptive, iterative merge sort inspired by
1072 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1073 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1074 /// two or more sorted sequences concatenated one after another.
1076 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1077 /// non-allocating insertion sort is used instead.
1082 /// let mut v = [-5, 4, 1, -3, 2];
1085 /// assert!(v == [-5, -3, 1, 2, 4]);
1087 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn sort(&mut self)
1092 merge_sort(self, |a
, b
| a
.lt(b
));
1095 /// Sorts the slice using `f` to extract a key to compare elements by.
1097 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1099 /// # Current implementation
1101 /// The current algorithm is an adaptive, iterative merge sort inspired by
1102 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1103 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1104 /// two or more sorted sequences concatenated one after another.
1106 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1107 /// non-allocating insertion sort is used instead.
1112 /// let mut v = [-5i32, 4, 1, -3, 2];
1114 /// v.sort_by_key(|k| k.abs());
1115 /// assert!(v == [1, 2, -3, 4, -5]);
1117 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1119 pub fn sort_by_key
<B
, F
>(&mut self, mut f
: F
)
1120 where F
: FnMut(&T
) -> B
, B
: Ord
1122 merge_sort(self, |a
, b
| f(a
).lt(&f(b
)));
1125 /// Sorts the slice using `compare` to compare elements.
1127 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1129 /// # Current implementation
1131 /// The current algorithm is an adaptive, iterative merge sort inspired by
1132 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1133 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1134 /// two or more sorted sequences concatenated one after another.
1136 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1137 /// non-allocating insertion sort is used instead.
1142 /// let mut v = [5, 4, 1, 3, 2];
1143 /// v.sort_by(|a, b| a.cmp(b));
1144 /// assert!(v == [1, 2, 3, 4, 5]);
1146 /// // reverse sorting
1147 /// v.sort_by(|a, b| b.cmp(a));
1148 /// assert!(v == [5, 4, 3, 2, 1]);
1150 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub fn sort_by
<F
>(&mut self, mut compare
: F
)
1153 where F
: FnMut(&T
, &T
) -> Ordering
1155 merge_sort(self, |a
, b
| compare(a
, b
) == Less
);
1158 /// Copies the elements from `src` into `self`.
1160 /// The length of `src` must be the same as `self`.
1164 /// This function will panic if the two slices have different lengths.
1169 /// let mut dst = [0, 0, 0];
1170 /// let src = [1, 2, 3];
1172 /// dst.clone_from_slice(&src);
1173 /// assert!(dst == [1, 2, 3]);
1175 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1176 pub fn clone_from_slice(&mut self, src
: &[T
]) where T
: Clone
{
1177 core_slice
::SliceExt
::clone_from_slice(self, src
)
1180 /// Copies all elements from `src` into `self`, using a memcpy.
1182 /// The length of `src` must be the same as `self`.
1186 /// This function will panic if the two slices have different lengths.
1191 /// let mut dst = [0, 0, 0];
1192 /// let src = [1, 2, 3];
1194 /// dst.copy_from_slice(&src);
1195 /// assert_eq!(src, dst);
1197 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1198 pub fn copy_from_slice(&mut self, src
: &[T
]) where T
: Copy
{
1199 core_slice
::SliceExt
::copy_from_slice(self, src
)
1203 /// Copies `self` into a new `Vec`.
1208 /// let s = [10, 40, 30];
1209 /// let x = s.to_vec();
1210 /// // Here, `s` and `x` can be modified independently.
1212 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub fn to_vec(&self) -> Vec
<T
>
1217 // NB see hack module in this file
1221 /// Converts `self` into a vector without clones or allocation.
1226 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1227 /// let x = s.into_vec();
1228 /// // `s` cannot be used anymore because it has been converted into `x`.
1230 /// assert_eq!(x, vec![10, 40, 30]);
1232 #[stable(feature = "rust1", since = "1.0.0")]
1234 pub fn into_vec(self: Box
<Self>) -> Vec
<T
> {
1235 // NB see hack module in this file
1236 hack
::into_vec(self)
1240 ////////////////////////////////////////////////////////////////////////////////
1241 // Extension traits for slices over specific kinds of data
1242 ////////////////////////////////////////////////////////////////////////////////
1243 #[unstable(feature = "slice_concat_ext",
1244 reason
= "trait should not have to exist",
1246 /// An extension trait for concatenating slices
1247 pub trait SliceConcatExt
<T
: ?Sized
> {
1248 #[unstable(feature = "slice_concat_ext",
1249 reason
= "trait should not have to exist",
1251 /// The resulting type after concatenation
1254 /// Flattens a slice of `T` into a single value `Self::Output`.
1259 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 fn concat(&self) -> Self::Output
;
1264 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1265 /// given separator between each.
1270 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1272 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1273 fn join(&self, sep
: &T
) -> Self::Output
;
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1277 fn connect(&self, sep
: &T
) -> Self::Output
;
1280 #[unstable(feature = "slice_concat_ext",
1281 reason
= "trait should not have to exist",
1283 impl<T
: Clone
, V
: Borrow
<[T
]>> SliceConcatExt
<T
> for [V
] {
1284 type Output
= Vec
<T
>;
1286 fn concat(&self) -> Vec
<T
> {
1287 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1288 let mut result
= Vec
::with_capacity(size
);
1290 result
.extend_from_slice(v
.borrow())
1295 fn join(&self, sep
: &T
) -> Vec
<T
> {
1296 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1297 let mut result
= Vec
::with_capacity(size
+ self.len());
1298 let mut first
= true;
1303 result
.push(sep
.clone())
1305 result
.extend_from_slice(v
.borrow())
1310 fn connect(&self, sep
: &T
) -> Vec
<T
> {
1315 ////////////////////////////////////////////////////////////////////////////////
1316 // Standard trait implementations for slices
1317 ////////////////////////////////////////////////////////////////////////////////
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<T
> Borrow
<[T
]> for Vec
<T
> {
1321 fn borrow(&self) -> &[T
] {
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<T
> BorrowMut
<[T
]> for Vec
<T
> {
1328 fn borrow_mut(&mut self) -> &mut [T
] {
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 impl<T
: Clone
> ToOwned
for [T
] {
1335 type Owned
= Vec
<T
>;
1337 fn to_owned(&self) -> Vec
<T
> {
1341 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1342 // definition, is not available. Since we don't require this method for testing purposes, I'll
1344 // NB see the slice::hack module in slice.rs for more information
1346 fn to_owned(&self) -> Vec
<T
> {
1347 panic
!("not available with cfg(test)")
1351 ////////////////////////////////////////////////////////////////////////////////
1353 ////////////////////////////////////////////////////////////////////////////////
1355 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
1357 /// This is the integral subroutine of insertion sort.
1358 fn insert_head
<T
, F
>(v
: &mut [T
], is_less
: &mut F
)
1359 where F
: FnMut(&T
, &T
) -> bool
1361 if v
.len() >= 2 && is_less(&v
[1], &v
[0]) {
1363 // There are three ways to implement insertion here:
1365 // 1. Swap adjacent elements until the first one gets to its final destination.
1366 // However, this way we copy data around more than is necessary. If elements are big
1367 // structures (costly to copy), this method will be slow.
1369 // 2. Iterate until the right place for the first element is found. Then shift the
1370 // elements succeeding it to make room for it and finally place it into the
1371 // remaining hole. This is a good method.
1373 // 3. Copy the first element into a temporary variable. Iterate until the right place
1374 // for it is found. As we go along, copy every traversed element into the slot
1375 // preceding it. Finally, copy data from the temporary variable into the remaining
1376 // hole. This method is very good. Benchmarks demonstrated slightly better
1377 // performance than with the 2nd method.
1379 // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
1380 let mut tmp
= NoDrop { value: ptr::read(&v[0]) }
;
1382 // Intermediate state of the insertion process is always tracked by `hole`, which
1383 // serves two purposes:
1384 // 1. Protects integrity of `v` from panics in `is_less`.
1385 // 2. Fills the remaining hole in `v` in the end.
1389 // If `is_less` panics at any point during the process, `hole` will get dropped and
1390 // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
1391 // initially held exactly once.
1392 let mut hole
= InsertionHole
{
1393 src
: &mut tmp
.value
,
1396 ptr
::copy_nonoverlapping(&v
[1], &mut v
[0], 1);
1398 for i
in 2..v
.len() {
1399 if !is_less(&v
[i
], &tmp
.value
) {
1402 ptr
::copy_nonoverlapping(&v
[i
], &mut v
[i
- 1], 1);
1403 hole
.dest
= &mut v
[i
];
1405 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
1409 // Holds a value, but never drops it.
1410 #[allow(unions_with_drop_fields)]
1415 // When dropped, copies from `src` into `dest`.
1416 struct InsertionHole
<T
> {
1421 impl<T
> Drop
for InsertionHole
<T
> {
1422 fn drop(&mut self) {
1423 unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
1428 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
1429 /// stores the result into `v[..]`.
1433 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
1434 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
1435 unsafe fn merge
<T
, F
>(v
: &mut [T
], mid
: usize, buf
: *mut T
, is_less
: &mut F
)
1436 where F
: FnMut(&T
, &T
) -> bool
1439 let v
= v
.as_mut_ptr();
1440 let v_mid
= v
.offset(mid
as isize);
1441 let v_end
= v
.offset(len
as isize);
1443 // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
1444 // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
1445 // copying the lesser (or greater) one into `v`.
1447 // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
1448 // consumed first, then we must copy whatever is left of the shorter run into the remaining
1451 // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
1452 // 1. Protects integrity of `v` from panics in `is_less`.
1453 // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
1457 // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
1458 // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
1459 // object it initially held exactly once.
1462 if mid
<= len
- mid
{
1463 // The left run is shorter.
1464 ptr
::copy_nonoverlapping(v
, buf
, mid
);
1467 end
: buf
.offset(mid
as isize),
1471 // Initially, these pointers point to the beginnings of their arrays.
1472 let left
= &mut hole
.start
;
1473 let mut right
= v_mid
;
1474 let out
= &mut hole
.dest
;
1476 while *left
< hole
.end
&& right
< v_end
{
1477 // Consume the lesser side.
1478 // If equal, prefer the left run to maintain stability.
1479 let to_copy
= if is_less(&*right
, &**left
) {
1480 get_and_increment(&mut right
)
1482 get_and_increment(left
)
1484 ptr
::copy_nonoverlapping(to_copy
, get_and_increment(out
), 1);
1487 // The right run is shorter.
1488 ptr
::copy_nonoverlapping(v_mid
, buf
, len
- mid
);
1491 end
: buf
.offset((len
- mid
) as isize),
1495 // Initially, these pointers point past the ends of their arrays.
1496 let left
= &mut hole
.dest
;
1497 let right
= &mut hole
.end
;
1498 let mut out
= v_end
;
1500 while v
< *left
&& buf
< *right
{
1501 // Consume the greater side.
1502 // If equal, prefer the right run to maintain stability.
1503 let to_copy
= if is_less(&*right
.offset(-1), &*left
.offset(-1)) {
1504 decrement_and_get(left
)
1506 decrement_and_get(right
)
1508 ptr
::copy_nonoverlapping(to_copy
, decrement_and_get(&mut out
), 1);
1511 // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
1512 // it will now be copied into the hole in `v`.
1514 unsafe fn get_and_increment
<T
>(ptr
: &mut *mut T
) -> *mut T
{
1516 *ptr
= ptr
.offset(1);
1520 unsafe fn decrement_and_get
<T
>(ptr
: &mut *mut T
) -> *mut T
{
1521 *ptr
= ptr
.offset(-1);
1525 // When dropped, copies the range `start..end` into `dest..`.
1526 struct MergeHole
<T
> {
1532 impl<T
> Drop
for MergeHole
<T
> {
1533 fn drop(&mut self) {
1534 // `T` is not a zero-sized type, so it's okay to divide by it's size.
1535 let len
= (self.end
as usize - self.start
as usize) / mem
::size_of
::<T
>();
1536 unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
1541 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
1542 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
1544 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1545 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1546 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1549 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1550 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1552 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
1553 fn merge_sort
<T
, F
>(v
: &mut [T
], mut is_less
: F
)
1554 where F
: FnMut(&T
, &T
) -> bool
1556 // Sorting has no meaningful behavior on zero-sized types.
1557 if size_of
::<T
>() == 0 {
1561 // FIXME #12092: These numbers are platform-specific and need more extensive testing/tuning.
1563 // If `v` has length up to `max_insertion`, simply switch to insertion sort because it is going
1564 // to perform better than merge sort. For bigger types `T`, the threshold is smaller.
1566 // Short runs are extended using insertion sort to span at least `min_run` elements, in order
1567 // to improve performance.
1568 let (max_insertion
, min_run
) = if size_of
::<T
>() <= 2 * mem
::size_of
::<usize>() {
1576 // Short arrays get sorted in-place via insertion sort to avoid allocations.
1577 if len
<= max_insertion
{
1579 for i
in (0..len
-1).rev() {
1580 insert_head(&mut v
[i
..], &mut is_less
);
1586 // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1587 // shallow copies of the contents of `v` without risking the dtors running on copies if
1588 // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1589 // which will always have length at most `len / 2`.
1590 let mut buf
= Vec
::with_capacity(len
/ 2);
1592 // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
1593 // strange decision, but consider the fact that merges more often go in the opposite direction
1594 // (forwards). According to benchmarks, merging forwards is slightly faster than merging
1595 // backwards. To conclude, identifying runs by traversing backwards improves performance.
1596 let mut runs
= vec
![];
1599 // Find the next natural run, and reverse it if it's strictly descending.
1600 let mut start
= end
- 1;
1604 if is_less(v
.get_unchecked(start
+ 1), v
.get_unchecked(start
)) {
1605 while start
> 0 && is_less(v
.get_unchecked(start
),
1606 v
.get_unchecked(start
- 1)) {
1609 v
[start
..end
].reverse();
1611 while start
> 0 && !is_less(v
.get_unchecked(start
),
1612 v
.get_unchecked(start
- 1)) {
1619 // Insert some more elements into the run if it's too short. Insertion sort is faster than
1620 // merge sort on short sequences, so this significantly improves performance.
1621 while start
> 0 && end
- start
< min_run
{
1623 insert_head(&mut v
[start
..end
], &mut is_less
);
1626 // Push this run onto the stack.
1633 // Merge some pairs of adjacent runs to satisfy the invariants.
1634 while let Some(r
) = collapse(&runs
) {
1635 let left
= runs
[r
+ 1];
1636 let right
= runs
[r
];
1638 merge(&mut v
[left
.start
.. right
.start
+ right
.len
], left
.len
, buf
.as_mut_ptr(),
1643 len
: left
.len
+ right
.len
,
1649 // Finally, exactly one run must remain in the stack.
1650 debug_assert
!(runs
.len() == 1 && runs
[0].start
== 0 && runs
[0].len
== len
);
1652 // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1653 // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1654 // algorithm should continue building a new run instead, `None` is returned.
1656 // TimSort is infamous for it's buggy implementations, as described here:
1657 // http://envisage-project.eu/timsort-specification-and-verification/
1659 // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1660 // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1661 // hold for *all* runs in the stack.
1663 // This function correctly checks invariants for the top four runs. Additionally, if the top
1664 // run starts at index 0, it will always demand a merge operation until the stack is fully
1665 // collapsed, in order to complete the sort.
1667 fn collapse(runs
: &[Run
]) -> Option
<usize> {
1669 if n
>= 2 && (runs
[n
- 1].start
== 0 ||
1670 runs
[n
- 2].len
<= runs
[n
- 1].len
||
1671 (n
>= 3 && runs
[n
- 3].len
<= runs
[n
- 2].len
+ runs
[n
- 1].len
) ||
1672 (n
>= 4 && runs
[n
- 4].len
<= runs
[n
- 3].len
+ runs
[n
- 2].len
)) {
1673 if n
>= 3 && runs
[n
- 3].len
< runs
[n
- 1].len
{
1683 #[derive(Clone, Copy)]