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 core
::cmp
::Ordering
::{self, Less}
;
101 use core
::mem
::size_of
;
104 use core
::slice
as core_slice
;
105 use core
::{u8, u16, u32}
;
107 use borrow
::{Borrow, BorrowMut, ToOwned}
;
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub use core
::slice
::{Chunks, Windows}
;
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub use core
::slice
::{Iter, IterMut}
;
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub use core
::slice
::{SplitMut, ChunksMut, Split}
;
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub use core
::slice
::{SplitN, RSplitN, SplitNMut, RSplitNMut}
;
119 #[unstable(feature = "slice_rsplit", issue = "41020")]
120 pub use core
::slice
::{RSplit, RSplitMut}
;
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub use core
::slice
::{from_raw_parts, from_raw_parts_mut}
;
123 #[unstable(feature = "from_ref", issue = "45703")]
124 pub use core
::slice
::{from_ref, from_ref_mut}
;
125 #[unstable(feature = "slice_get_slice", issue = "35729")]
126 pub use core
::slice
::SliceIndex
;
127 #[unstable(feature = "exact_chunks", issue = "47115")]
128 pub use core
::slice
::{ExactChunks, ExactChunksMut}
;
130 ////////////////////////////////////////////////////////////////////////////////
131 // Basic slice extension methods
132 ////////////////////////////////////////////////////////////////////////////////
134 // HACK(japaric) needed for the implementation of `vec!` macro during testing
135 // NB see the hack module in this file for more details
137 pub use self::hack
::into_vec
;
139 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
140 // NB see the hack module in this file for more details
142 pub use self::hack
::to_vec
;
144 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
145 // functions are actually methods that are in `impl [T]` but not in
146 // `core::slice::SliceExt` - we need to supply these functions for the
147 // `test_permutations` test
153 use string
::ToString
;
156 pub fn into_vec
<T
>(mut b
: Box
<[T
]>) -> Vec
<T
> {
158 let xs
= Vec
::from_raw_parts(b
.as_mut_ptr(), b
.len(), b
.len());
165 pub fn to_vec
<T
>(s
: &[T
]) -> Vec
<T
>
168 let mut vector
= Vec
::with_capacity(s
.len());
169 vector
.extend_from_slice(s
);
177 /// Returns the number of elements in the slice.
182 /// let a = [1, 2, 3];
183 /// assert_eq!(a.len(), 3);
185 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn len(&self) -> usize {
188 core_slice
::SliceExt
::len(self)
191 /// Returns `true` if the slice has a length of 0.
196 /// let a = [1, 2, 3];
197 /// assert!(!a.is_empty());
199 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn is_empty(&self) -> bool
{
202 core_slice
::SliceExt
::is_empty(self)
205 /// Returns the first element of the slice, or `None` if it is empty.
210 /// let v = [10, 40, 30];
211 /// assert_eq!(Some(&10), v.first());
213 /// let w: &[i32] = &[];
214 /// assert_eq!(None, w.first());
216 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn first(&self) -> Option
<&T
> {
219 core_slice
::SliceExt
::first(self)
222 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
227 /// let x = &mut [0, 1, 2];
229 /// if let Some(first) = x.first_mut() {
232 /// assert_eq!(x, &[5, 1, 2]);
234 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn first_mut(&mut self) -> Option
<&mut T
> {
237 core_slice
::SliceExt
::first_mut(self)
240 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
245 /// let x = &[0, 1, 2];
247 /// if let Some((first, elements)) = x.split_first() {
248 /// assert_eq!(first, &0);
249 /// assert_eq!(elements, &[1, 2]);
252 #[stable(feature = "slice_splits", since = "1.5.0")]
254 pub fn split_first(&self) -> Option
<(&T
, &[T
])> {
255 core_slice
::SliceExt
::split_first(self)
258 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
263 /// let x = &mut [0, 1, 2];
265 /// if let Some((first, elements)) = x.split_first_mut() {
270 /// assert_eq!(x, &[3, 4, 5]);
272 #[stable(feature = "slice_splits", since = "1.5.0")]
274 pub fn split_first_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
275 core_slice
::SliceExt
::split_first_mut(self)
278 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
283 /// let x = &[0, 1, 2];
285 /// if let Some((last, elements)) = x.split_last() {
286 /// assert_eq!(last, &2);
287 /// assert_eq!(elements, &[0, 1]);
290 #[stable(feature = "slice_splits", since = "1.5.0")]
292 pub fn split_last(&self) -> Option
<(&T
, &[T
])> {
293 core_slice
::SliceExt
::split_last(self)
297 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
302 /// let x = &mut [0, 1, 2];
304 /// if let Some((last, elements)) = x.split_last_mut() {
309 /// assert_eq!(x, &[4, 5, 3]);
311 #[stable(feature = "slice_splits", since = "1.5.0")]
313 pub fn split_last_mut(&mut self) -> Option
<(&mut T
, &mut [T
])> {
314 core_slice
::SliceExt
::split_last_mut(self)
317 /// Returns the last element of the slice, or `None` if it is empty.
322 /// let v = [10, 40, 30];
323 /// assert_eq!(Some(&30), v.last());
325 /// let w: &[i32] = &[];
326 /// assert_eq!(None, w.last());
328 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn last(&self) -> Option
<&T
> {
331 core_slice
::SliceExt
::last(self)
334 /// Returns a mutable pointer to the last item in the slice.
339 /// let x = &mut [0, 1, 2];
341 /// if let Some(last) = x.last_mut() {
344 /// assert_eq!(x, &[0, 1, 10]);
346 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn last_mut(&mut self) -> Option
<&mut T
> {
349 core_slice
::SliceExt
::last_mut(self)
352 /// Returns a reference to an element or subslice depending on the type of
355 /// - If given a position, returns a reference to the element at that
356 /// position or `None` if out of bounds.
357 /// - If given a range, returns the subslice corresponding to that range,
358 /// or `None` if out of bounds.
363 /// let v = [10, 40, 30];
364 /// assert_eq!(Some(&40), v.get(1));
365 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
366 /// assert_eq!(None, v.get(3));
367 /// assert_eq!(None, v.get(0..4));
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn get
<I
>(&self, index
: I
) -> Option
<&I
::Output
>
372 where I
: SliceIndex
<Self>
374 core_slice
::SliceExt
::get(self, index
)
377 /// Returns a mutable reference to an element or subslice depending on the
378 /// type of index (see [`get`]) or `None` if the index is out of bounds.
380 /// [`get`]: #method.get
385 /// let x = &mut [0, 1, 2];
387 /// if let Some(elem) = x.get_mut(1) {
390 /// assert_eq!(x, &[0, 42, 2]);
392 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn get_mut
<I
>(&mut self, index
: I
) -> Option
<&mut I
::Output
>
395 where I
: SliceIndex
<Self>
397 core_slice
::SliceExt
::get_mut(self, index
)
400 /// Returns a reference to an element or subslice, without doing bounds
403 /// This is generally not recommended, use with caution! For a safe
404 /// alternative see [`get`].
406 /// [`get`]: #method.get
411 /// let x = &[1, 2, 4];
414 /// assert_eq!(x.get_unchecked(1), &2);
417 #[stable(feature = "rust1", since = "1.0.0")]
419 pub unsafe fn get_unchecked
<I
>(&self, index
: I
) -> &I
::Output
420 where I
: SliceIndex
<Self>
422 core_slice
::SliceExt
::get_unchecked(self, index
)
425 /// Returns a mutable reference to an element or subslice, without doing
428 /// This is generally not recommended, use with caution! For a safe
429 /// alternative see [`get_mut`].
431 /// [`get_mut`]: #method.get_mut
436 /// let x = &mut [1, 2, 4];
439 /// let elem = x.get_unchecked_mut(1);
442 /// assert_eq!(x, &[1, 13, 4]);
444 #[stable(feature = "rust1", since = "1.0.0")]
446 pub unsafe fn get_unchecked_mut
<I
>(&mut self, index
: I
) -> &mut I
::Output
447 where I
: SliceIndex
<Self>
449 core_slice
::SliceExt
::get_unchecked_mut(self, index
)
452 /// Returns a raw pointer to the slice's buffer.
454 /// The caller must ensure that the slice outlives the pointer this
455 /// function returns, or else it will end up pointing to garbage.
457 /// Modifying the container referenced by this slice may cause its buffer
458 /// to be reallocated, which would also make any pointers to it invalid.
463 /// let x = &[1, 2, 4];
464 /// let x_ptr = x.as_ptr();
467 /// for i in 0..x.len() {
468 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
472 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn as_ptr(&self) -> *const T
{
475 core_slice
::SliceExt
::as_ptr(self)
478 /// Returns an unsafe mutable pointer to the slice's buffer.
480 /// The caller must ensure that the slice outlives the pointer this
481 /// function returns, or else it will end up pointing to garbage.
483 /// Modifying the container referenced by this slice may cause its buffer
484 /// to be reallocated, which would also make any pointers to it invalid.
489 /// let x = &mut [1, 2, 4];
490 /// let x_ptr = x.as_mut_ptr();
493 /// for i in 0..x.len() {
494 /// *x_ptr.offset(i as isize) += 2;
497 /// assert_eq!(x, &[3, 4, 6]);
499 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn as_mut_ptr(&mut self) -> *mut T
{
502 core_slice
::SliceExt
::as_mut_ptr(self)
505 /// Swaps two elements in the slice.
509 /// * a - The index of the first element
510 /// * b - The index of the second element
514 /// Panics if `a` or `b` are out of bounds.
519 /// let mut v = ["a", "b", "c", "d"];
521 /// assert!(v == ["a", "d", "c", "b"]);
523 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn swap(&mut self, a
: usize, b
: usize) {
526 core_slice
::SliceExt
::swap(self, a
, b
)
529 /// Reverses the order of elements in the slice, in place.
534 /// let mut v = [1, 2, 3];
536 /// assert!(v == [3, 2, 1]);
538 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn reverse(&mut self) {
541 core_slice
::SliceExt
::reverse(self)
544 /// Returns an iterator over the slice.
549 /// let x = &[1, 2, 4];
550 /// let mut iterator = x.iter();
552 /// assert_eq!(iterator.next(), Some(&1));
553 /// assert_eq!(iterator.next(), Some(&2));
554 /// assert_eq!(iterator.next(), Some(&4));
555 /// assert_eq!(iterator.next(), None);
557 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn iter(&self) -> Iter
<T
> {
560 core_slice
::SliceExt
::iter(self)
563 /// Returns an iterator that allows modifying each value.
568 /// let x = &mut [1, 2, 4];
569 /// for elem in x.iter_mut() {
572 /// assert_eq!(x, &[3, 4, 6]);
574 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn iter_mut(&mut self) -> IterMut
<T
> {
577 core_slice
::SliceExt
::iter_mut(self)
580 /// Returns an iterator over all contiguous windows of length
581 /// `size`. The windows overlap. If the slice is shorter than
582 /// `size`, the iterator returns no values.
586 /// Panics if `size` is 0.
591 /// let slice = ['r', 'u', 's', 't'];
592 /// let mut iter = slice.windows(2);
593 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
594 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
595 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
596 /// assert!(iter.next().is_none());
599 /// If the slice is shorter than `size`:
602 /// let slice = ['f', 'o', 'o'];
603 /// let mut iter = slice.windows(4);
604 /// assert!(iter.next().is_none());
606 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn windows(&self, size
: usize) -> Windows
<T
> {
609 core_slice
::SliceExt
::windows(self, size
)
612 /// Returns an iterator over `chunk_size` elements of the slice at a
613 /// time. The chunks are slices and do not overlap. If `chunk_size` does
614 /// not divide the length of the slice, then the last chunk will
615 /// not have length `chunk_size`.
617 /// See [`exact_chunks`] for a variant of this iterator that returns chunks
618 /// of always exactly `chunk_size` elements.
622 /// Panics if `chunk_size` is 0.
627 /// let slice = ['l', 'o', 'r', 'e', 'm'];
628 /// let mut iter = slice.chunks(2);
629 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
630 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
631 /// assert_eq!(iter.next().unwrap(), &['m']);
632 /// assert!(iter.next().is_none());
635 /// [`exact_chunks`]: #method.exact_chunks
636 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn chunks(&self, chunk_size
: usize) -> Chunks
<T
> {
639 core_slice
::SliceExt
::chunks(self, chunk_size
)
642 /// Returns an iterator over `chunk_size` elements of the slice at a
643 /// time. The chunks are slices and do not overlap. If `chunk_size` does
644 /// not divide the length of the slice, then the last up to `chunk_size-1`
645 /// elements will be omitted.
647 /// Due to each chunk having exactly `chunk_size` elements, the compiler
648 /// can often optimize the resulting code better than in the case of
653 /// Panics if `chunk_size` is 0.
658 /// #![feature(exact_chunks)]
660 /// let slice = ['l', 'o', 'r', 'e', 'm'];
661 /// let mut iter = slice.exact_chunks(2);
662 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
663 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
664 /// assert!(iter.next().is_none());
667 /// [`chunks`]: #method.chunks
668 #[unstable(feature = "exact_chunks", issue = "47115")]
670 pub fn exact_chunks(&self, chunk_size
: usize) -> ExactChunks
<T
> {
671 core_slice
::SliceExt
::exact_chunks(self, chunk_size
)
674 /// Returns an iterator over `chunk_size` elements of the slice at a time.
675 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
676 /// not divide the length of the slice, then the last chunk will not
677 /// have length `chunk_size`.
679 /// See [`exact_chunks_mut`] for a variant of this iterator that returns chunks
680 /// of always exactly `chunk_size` elements.
684 /// Panics if `chunk_size` is 0.
689 /// let v = &mut [0, 0, 0, 0, 0];
690 /// let mut count = 1;
692 /// for chunk in v.chunks_mut(2) {
693 /// for elem in chunk.iter_mut() {
698 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
701 /// [`exact_chunks_mut`]: #method.exact_chunks_mut
702 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn chunks_mut(&mut self, chunk_size
: usize) -> ChunksMut
<T
> {
705 core_slice
::SliceExt
::chunks_mut(self, chunk_size
)
708 /// Returns an iterator over `chunk_size` elements of the slice at a time.
709 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
710 /// not divide the length of the slice, then the last up to `chunk_size-1`
711 /// elements will be omitted.
714 /// Due to each chunk having exactly `chunk_size` elements, the compiler
715 /// can often optimize the resulting code better than in the case of
720 /// Panics if `chunk_size` is 0.
725 /// #![feature(exact_chunks)]
727 /// let v = &mut [0, 0, 0, 0, 0];
728 /// let mut count = 1;
730 /// for chunk in v.exact_chunks_mut(2) {
731 /// for elem in chunk.iter_mut() {
736 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
739 /// [`chunks_mut`]: #method.chunks_mut
740 #[unstable(feature = "exact_chunks", issue = "47115")]
742 pub fn exact_chunks_mut(&mut self, chunk_size
: usize) -> ExactChunksMut
<T
> {
743 core_slice
::SliceExt
::exact_chunks_mut(self, chunk_size
)
746 /// Divides one slice into two at an index.
748 /// The first will contain all indices from `[0, mid)` (excluding
749 /// the index `mid` itself) and the second will contain all
750 /// indices from `[mid, len)` (excluding the index `len` itself).
754 /// Panics if `mid > len`.
759 /// let v = [1, 2, 3, 4, 5, 6];
762 /// let (left, right) = v.split_at(0);
763 /// assert!(left == []);
764 /// assert!(right == [1, 2, 3, 4, 5, 6]);
768 /// let (left, right) = v.split_at(2);
769 /// assert!(left == [1, 2]);
770 /// assert!(right == [3, 4, 5, 6]);
774 /// let (left, right) = v.split_at(6);
775 /// assert!(left == [1, 2, 3, 4, 5, 6]);
776 /// assert!(right == []);
779 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn split_at(&self, mid
: usize) -> (&[T
], &[T
]) {
782 core_slice
::SliceExt
::split_at(self, mid
)
785 /// Divides one mutable slice into two at an index.
787 /// The first will contain all indices from `[0, mid)` (excluding
788 /// the index `mid` itself) and the second will contain all
789 /// indices from `[mid, len)` (excluding the index `len` itself).
793 /// Panics if `mid > len`.
798 /// let mut v = [1, 0, 3, 0, 5, 6];
799 /// // scoped to restrict the lifetime of the borrows
801 /// let (left, right) = v.split_at_mut(2);
802 /// assert!(left == [1, 0]);
803 /// assert!(right == [3, 0, 5, 6]);
807 /// assert!(v == [1, 2, 3, 4, 5, 6]);
809 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn split_at_mut(&mut self, mid
: usize) -> (&mut [T
], &mut [T
]) {
812 core_slice
::SliceExt
::split_at_mut(self, mid
)
815 /// Returns an iterator over subslices separated by elements that match
816 /// `pred`. The matched element is not contained in the subslices.
821 /// let slice = [10, 40, 33, 20];
822 /// let mut iter = slice.split(|num| num % 3 == 0);
824 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
825 /// assert_eq!(iter.next().unwrap(), &[20]);
826 /// assert!(iter.next().is_none());
829 /// If the first element is matched, an empty slice will be the first item
830 /// returned by the iterator. Similarly, if the last element in the slice
831 /// is matched, an empty slice will be the last item returned by the
835 /// let slice = [10, 40, 33];
836 /// let mut iter = slice.split(|num| num % 3 == 0);
838 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
839 /// assert_eq!(iter.next().unwrap(), &[]);
840 /// assert!(iter.next().is_none());
843 /// If two matched elements are directly adjacent, an empty slice will be
844 /// present between them:
847 /// let slice = [10, 6, 33, 20];
848 /// let mut iter = slice.split(|num| num % 3 == 0);
850 /// assert_eq!(iter.next().unwrap(), &[10]);
851 /// assert_eq!(iter.next().unwrap(), &[]);
852 /// assert_eq!(iter.next().unwrap(), &[20]);
853 /// assert!(iter.next().is_none());
855 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn split
<F
>(&self, pred
: F
) -> Split
<T
, F
>
858 where F
: FnMut(&T
) -> bool
860 core_slice
::SliceExt
::split(self, pred
)
863 /// Returns an iterator over mutable subslices separated by elements that
864 /// match `pred`. The matched element is not contained in the subslices.
869 /// let mut v = [10, 40, 30, 20, 60, 50];
871 /// for group in v.split_mut(|num| *num % 3 == 0) {
874 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
876 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn split_mut
<F
>(&mut self, pred
: F
) -> SplitMut
<T
, F
>
879 where F
: FnMut(&T
) -> bool
881 core_slice
::SliceExt
::split_mut(self, pred
)
884 /// Returns an iterator over subslices separated by elements that match
885 /// `pred`, starting at the end of the slice and working backwards.
886 /// The matched element is not contained in the subslices.
891 /// #![feature(slice_rsplit)]
893 /// let slice = [11, 22, 33, 0, 44, 55];
894 /// let mut iter = slice.rsplit(|num| *num == 0);
896 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
897 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
898 /// assert_eq!(iter.next(), None);
901 /// As with `split()`, if the first or last element is matched, an empty
902 /// slice will be the first (or last) item returned by the iterator.
905 /// #![feature(slice_rsplit)]
907 /// let v = &[0, 1, 1, 2, 3, 5, 8];
908 /// let mut it = v.rsplit(|n| *n % 2 == 0);
909 /// assert_eq!(it.next().unwrap(), &[]);
910 /// assert_eq!(it.next().unwrap(), &[3, 5]);
911 /// assert_eq!(it.next().unwrap(), &[1, 1]);
912 /// assert_eq!(it.next().unwrap(), &[]);
913 /// assert_eq!(it.next(), None);
915 #[unstable(feature = "slice_rsplit", issue = "41020")]
917 pub fn rsplit
<F
>(&self, pred
: F
) -> RSplit
<T
, F
>
918 where F
: FnMut(&T
) -> bool
920 core_slice
::SliceExt
::rsplit(self, pred
)
923 /// Returns an iterator over mutable subslices separated by elements that
924 /// match `pred`, starting at the end of the slice and working
925 /// backwards. The matched element is not contained in the subslices.
930 /// #![feature(slice_rsplit)]
932 /// let mut v = [100, 400, 300, 200, 600, 500];
934 /// let mut count = 0;
935 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
937 /// group[0] = count;
939 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
942 #[unstable(feature = "slice_rsplit", issue = "41020")]
944 pub fn rsplit_mut
<F
>(&mut self, pred
: F
) -> RSplitMut
<T
, F
>
945 where F
: FnMut(&T
) -> bool
947 core_slice
::SliceExt
::rsplit_mut(self, pred
)
950 /// Returns an iterator over subslices separated by elements that match
951 /// `pred`, limited to returning at most `n` items. The matched element is
952 /// not contained in the subslices.
954 /// The last element returned, if any, will contain the remainder of the
959 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
963 /// let v = [10, 40, 30, 20, 60, 50];
965 /// for group in v.splitn(2, |num| *num % 3 == 0) {
966 /// println!("{:?}", group);
969 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn splitn
<F
>(&self, n
: usize, pred
: F
) -> SplitN
<T
, F
>
972 where F
: FnMut(&T
) -> bool
974 core_slice
::SliceExt
::splitn(self, n
, pred
)
977 /// Returns an iterator over subslices separated by elements that match
978 /// `pred`, limited to returning at most `n` items. The matched element is
979 /// not contained in the subslices.
981 /// The last element returned, if any, will contain the remainder of the
987 /// let mut v = [10, 40, 30, 20, 60, 50];
989 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
992 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
994 #[stable(feature = "rust1", since = "1.0.0")]
996 pub fn splitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> SplitNMut
<T
, F
>
997 where F
: FnMut(&T
) -> bool
999 core_slice
::SliceExt
::splitn_mut(self, n
, pred
)
1002 /// Returns an iterator over subslices separated by elements that match
1003 /// `pred` limited to returning at most `n` items. This starts at the end of
1004 /// the slice and works backwards. The matched element is not contained in
1007 /// The last element returned, if any, will contain the remainder of the
1012 /// Print the slice split once, starting from the end, by numbers divisible
1013 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1016 /// let v = [10, 40, 30, 20, 60, 50];
1018 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1019 /// println!("{:?}", group);
1022 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub fn rsplitn
<F
>(&self, n
: usize, pred
: F
) -> RSplitN
<T
, F
>
1025 where F
: FnMut(&T
) -> bool
1027 core_slice
::SliceExt
::rsplitn(self, n
, pred
)
1030 /// Returns an iterator over subslices separated by elements that match
1031 /// `pred` limited to returning at most `n` items. This starts at the end of
1032 /// the slice and works backwards. The matched element is not contained in
1035 /// The last element returned, if any, will contain the remainder of the
1041 /// let mut s = [10, 40, 30, 20, 60, 50];
1043 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1046 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1048 #[stable(feature = "rust1", since = "1.0.0")]
1050 pub fn rsplitn_mut
<F
>(&mut self, n
: usize, pred
: F
) -> RSplitNMut
<T
, F
>
1051 where F
: FnMut(&T
) -> bool
1053 core_slice
::SliceExt
::rsplitn_mut(self, n
, pred
)
1056 /// Returns `true` if the slice contains an element with the given value.
1061 /// let v = [10, 40, 30];
1062 /// assert!(v.contains(&30));
1063 /// assert!(!v.contains(&50));
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub fn contains(&self, x
: &T
) -> bool
1069 core_slice
::SliceExt
::contains(self, x
)
1072 /// Returns `true` if `needle` is a prefix of the slice.
1077 /// let v = [10, 40, 30];
1078 /// assert!(v.starts_with(&[10]));
1079 /// assert!(v.starts_with(&[10, 40]));
1080 /// assert!(!v.starts_with(&[50]));
1081 /// assert!(!v.starts_with(&[10, 50]));
1084 /// Always returns `true` if `needle` is an empty slice:
1087 /// let v = &[10, 40, 30];
1088 /// assert!(v.starts_with(&[]));
1089 /// let v: &[u8] = &[];
1090 /// assert!(v.starts_with(&[]));
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub fn starts_with(&self, needle
: &[T
]) -> bool
1096 core_slice
::SliceExt
::starts_with(self, needle
)
1099 /// Returns `true` if `needle` is a suffix of the slice.
1104 /// let v = [10, 40, 30];
1105 /// assert!(v.ends_with(&[30]));
1106 /// assert!(v.ends_with(&[40, 30]));
1107 /// assert!(!v.ends_with(&[50]));
1108 /// assert!(!v.ends_with(&[50, 30]));
1111 /// Always returns `true` if `needle` is an empty slice:
1114 /// let v = &[10, 40, 30];
1115 /// assert!(v.ends_with(&[]));
1116 /// let v: &[u8] = &[];
1117 /// assert!(v.ends_with(&[]));
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn ends_with(&self, needle
: &[T
]) -> bool
1123 core_slice
::SliceExt
::ends_with(self, needle
)
1126 /// Binary searches this sorted slice for a given element.
1128 /// If the value is found then `Ok` is returned, containing the
1129 /// index of the matching element; if the value is not found then
1130 /// `Err` is returned, containing the index where a matching
1131 /// element could be inserted while maintaining sorted order.
1135 /// Looks up a series of four elements. The first is found, with a
1136 /// uniquely determined position; the second and third are not
1137 /// found; the fourth could match any position in `[1, 4]`.
1140 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1142 /// assert_eq!(s.binary_search(&13), Ok(9));
1143 /// assert_eq!(s.binary_search(&4), Err(7));
1144 /// assert_eq!(s.binary_search(&100), Err(13));
1145 /// let r = s.binary_search(&1);
1146 /// assert!(match r { Ok(1...4) => true, _ => false, });
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub fn binary_search(&self, x
: &T
) -> Result
<usize, usize>
1152 core_slice
::SliceExt
::binary_search(self, x
)
1155 /// Binary searches this sorted slice with a comparator function.
1157 /// The comparator function should implement an order consistent
1158 /// with the sort order of the underlying slice, returning an
1159 /// order code that indicates whether its argument is `Less`,
1160 /// `Equal` or `Greater` the desired target.
1162 /// If a matching value is found then returns `Ok`, containing
1163 /// the index for the matched element; if no match is found then
1164 /// `Err` is returned, containing the index where a matching
1165 /// element could be inserted while maintaining sorted order.
1169 /// Looks up a series of four elements. The first is found, with a
1170 /// uniquely determined position; the second and third are not
1171 /// found; the fourth could match any position in `[1, 4]`.
1174 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1177 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1179 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1181 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1183 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1184 /// assert!(match r { Ok(1...4) => true, _ => false, });
1186 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub fn binary_search_by
<'a
, F
>(&'a
self, f
: F
) -> Result
<usize, usize>
1189 where F
: FnMut(&'a T
) -> Ordering
1191 core_slice
::SliceExt
::binary_search_by(self, f
)
1194 /// Binary searches this sorted slice with a key extraction function.
1196 /// Assumes that the slice is sorted by the key, for instance with
1197 /// [`sort_by_key`] using the same key extraction function.
1199 /// If a matching value is found then returns `Ok`, containing the
1200 /// index for the matched element; if no match is found then `Err`
1201 /// is returned, containing the index where a matching element could
1202 /// be inserted while maintaining sorted order.
1204 /// [`sort_by_key`]: #method.sort_by_key
1208 /// Looks up a series of four elements in a slice of pairs sorted by
1209 /// their second elements. The first is found, with a uniquely
1210 /// determined position; the second and third are not found; the
1211 /// fourth could match any position in `[1, 4]`.
1214 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1215 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1216 /// (1, 21), (2, 34), (4, 55)];
1218 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1219 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1220 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1221 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1222 /// assert!(match r { Ok(1...4) => true, _ => false, });
1224 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1226 pub fn binary_search_by_key
<'a
, B
, F
>(&'a
self, b
: &B
, f
: F
) -> Result
<usize, usize>
1227 where F
: FnMut(&'a T
) -> B
,
1230 core_slice
::SliceExt
::binary_search_by_key(self, b
, f
)
1233 /// Sorts the slice.
1235 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1237 /// When applicable, unstable sorting is preferred because it is generally faster than stable
1238 /// sorting and it doesn't allocate auxiliary memory.
1239 /// See [`sort_unstable`](#method.sort_unstable).
1241 /// # Current implementation
1243 /// The current algorithm is an adaptive, iterative merge sort inspired by
1244 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1245 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1246 /// two or more sorted sequences concatenated one after another.
1248 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1249 /// non-allocating insertion sort is used instead.
1254 /// let mut v = [-5, 4, 1, -3, 2];
1257 /// assert!(v == [-5, -3, 1, 2, 4]);
1259 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn sort(&mut self)
1264 merge_sort(self, |a
, b
| a
.lt(b
));
1267 /// Sorts the slice with a comparator function.
1269 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1271 /// When applicable, unstable sorting is preferred because it is generally faster than stable
1272 /// sorting and it doesn't allocate auxiliary memory.
1273 /// See [`sort_unstable_by`](#method.sort_unstable_by).
1275 /// # Current implementation
1277 /// The current algorithm is an adaptive, iterative merge sort inspired by
1278 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1279 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1280 /// two or more sorted sequences concatenated one after another.
1282 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1283 /// non-allocating insertion sort is used instead.
1288 /// let mut v = [5, 4, 1, 3, 2];
1289 /// v.sort_by(|a, b| a.cmp(b));
1290 /// assert!(v == [1, 2, 3, 4, 5]);
1292 /// // reverse sorting
1293 /// v.sort_by(|a, b| b.cmp(a));
1294 /// assert!(v == [5, 4, 3, 2, 1]);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1298 pub fn sort_by
<F
>(&mut self, mut compare
: F
)
1299 where F
: FnMut(&T
, &T
) -> Ordering
1301 merge_sort(self, |a
, b
| compare(a
, b
) == Less
);
1304 /// Sorts the slice with a key extraction function.
1306 /// This sort is stable (i.e. does not reorder equal elements) and `O(m n log(m n))`
1307 /// worst-case, where the key function is `O(m)`.
1309 /// When applicable, unstable sorting is preferred because it is generally faster than stable
1310 /// sorting and it doesn't allocate auxiliary memory.
1311 /// See [`sort_unstable_by_key`](#method.sort_unstable_by_key).
1313 /// # Current implementation
1315 /// The current algorithm is an adaptive, iterative merge sort inspired by
1316 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1317 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1318 /// two or more sorted sequences concatenated one after another.
1320 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1321 /// non-allocating insertion sort is used instead.
1326 /// let mut v = [-5i32, 4, 1, -3, 2];
1328 /// v.sort_by_key(|k| k.abs());
1329 /// assert!(v == [1, 2, -3, 4, -5]);
1331 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1333 pub fn sort_by_key
<K
, F
>(&mut self, mut f
: F
)
1334 where F
: FnMut(&T
) -> K
, K
: Ord
1336 merge_sort(self, |a
, b
| f(a
).lt(&f(b
)));
1339 /// Sorts the slice with a key extraction function.
1341 /// During sorting, the key function is called only once per element.
1343 /// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)`
1344 /// worst-case, where the key function is `O(m)`.
1346 /// For simple key functions (e.g. functions that are property accesses or
1347 /// basic operations), [`sort_by_key`](#method.sort_by_key) is likely to be
1350 /// # Current implementation
1352 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1353 /// which combines the fast average case of randomized quicksort with the fast worst case of
1354 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1355 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1356 /// deterministic behavior.
1358 /// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
1359 /// length of the slice.
1364 /// #![feature(slice_sort_by_cached_key)]
1365 /// let mut v = [-5i32, 4, 32, -3, 2];
1367 /// v.sort_by_cached_key(|k| k.to_string());
1368 /// assert!(v == [-3, -5, 2, 32, 4]);
1371 /// [pdqsort]: https://github.com/orlp/pdqsort
1372 #[unstable(feature = "slice_sort_by_cached_key", issue = "34447")]
1374 pub fn sort_by_cached_key
<K
, F
>(&mut self, f
: F
)
1375 where F
: FnMut(&T
) -> K
, K
: Ord
1377 // Helper macro for indexing our vector by the smallest possible type, to reduce allocation.
1378 macro_rules
! sort_by_key
{
1379 ($t
:ty
, $slice
:ident
, $f
:ident
) => ({
1380 let mut indices
: Vec
<_
> =
1381 $slice
.iter().map($f
).enumerate().map(|(i
, k
)| (k
, i
as $t
)).collect();
1382 // The elements of `indices` are unique, as they are indexed, so any sort will be
1383 // stable with respect to the original slice. We use `sort_unstable` here because
1384 // it requires less memory allocation.
1385 indices
.sort_unstable();
1386 for i
in 0..$slice
.len() {
1387 let mut index
= indices
[i
].1;
1388 while (index
as usize) < i
{
1389 index
= indices
[index
as usize].1;
1391 indices
[i
].1 = index
;
1392 $slice
.swap(i
, index
as usize);
1397 let sz_u8
= mem
::size_of
::<(K
, u8)>();
1398 let sz_u16
= mem
::size_of
::<(K
, u16)>();
1399 let sz_u32
= mem
::size_of
::<(K
, u32)>();
1400 let sz_usize
= mem
::size_of
::<(K
, usize)>();
1402 let len
= self.len();
1403 if sz_u8
< sz_u16
&& len
<= ( u8::MAX
as usize) { return sort_by_key!( u8, self, f) }
1404 if sz_u16
< sz_u32
&& len
<= (u16::MAX
as usize) { return sort_by_key!(u16, self, f) }
1405 if sz_u32
< sz_usize
&& len
<= (u32::MAX
as usize) { return sort_by_key!(u32, self, f) }
1406 sort_by_key
!(usize, self, f
)
1409 /// Sorts the slice, but may not preserve the order of equal elements.
1411 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1412 /// and `O(n log n)` worst-case.
1414 /// # Current implementation
1416 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1417 /// which combines the fast average case of randomized quicksort with the fast worst case of
1418 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1419 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1420 /// deterministic behavior.
1422 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1423 /// slice consists of several concatenated sorted sequences.
1428 /// let mut v = [-5, 4, 1, -3, 2];
1430 /// v.sort_unstable();
1431 /// assert!(v == [-5, -3, 1, 2, 4]);
1434 /// [pdqsort]: https://github.com/orlp/pdqsort
1435 #[stable(feature = "sort_unstable", since = "1.20.0")]
1437 pub fn sort_unstable(&mut self)
1440 core_slice
::SliceExt
::sort_unstable(self);
1443 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1446 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1447 /// and `O(n log n)` worst-case.
1449 /// # Current implementation
1451 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1452 /// which combines the fast average case of randomized quicksort with the fast worst case of
1453 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1454 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1455 /// deterministic behavior.
1457 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1458 /// slice consists of several concatenated sorted sequences.
1463 /// let mut v = [5, 4, 1, 3, 2];
1464 /// v.sort_unstable_by(|a, b| a.cmp(b));
1465 /// assert!(v == [1, 2, 3, 4, 5]);
1467 /// // reverse sorting
1468 /// v.sort_unstable_by(|a, b| b.cmp(a));
1469 /// assert!(v == [5, 4, 3, 2, 1]);
1472 /// [pdqsort]: https://github.com/orlp/pdqsort
1473 #[stable(feature = "sort_unstable", since = "1.20.0")]
1475 pub fn sort_unstable_by
<F
>(&mut self, compare
: F
)
1476 where F
: FnMut(&T
, &T
) -> Ordering
1478 core_slice
::SliceExt
::sort_unstable_by(self, compare
);
1481 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1484 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1485 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1487 /// # Current implementation
1489 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1490 /// which combines the fast average case of randomized quicksort with the fast worst case of
1491 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1492 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1493 /// deterministic behavior.
1498 /// let mut v = [-5i32, 4, 1, -3, 2];
1500 /// v.sort_unstable_by_key(|k| k.abs());
1501 /// assert!(v == [1, 2, -3, 4, -5]);
1504 /// [pdqsort]: https://github.com/orlp/pdqsort
1505 #[stable(feature = "sort_unstable", since = "1.20.0")]
1507 pub fn sort_unstable_by_key
<K
, F
>(&mut self, f
: F
)
1508 where F
: FnMut(&T
) -> K
, K
: Ord
1510 core_slice
::SliceExt
::sort_unstable_by_key(self, f
);
1513 /// Rotates the slice in-place such that the first `mid` elements of the
1514 /// slice move to the end while the last `self.len() - mid` elements move to
1515 /// the front. After calling `rotate_left`, the element previously at index
1516 /// `mid` will become the first element in the slice.
1520 /// This function will panic if `mid` is greater than the length of the
1521 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1526 /// Takes linear (in `self.len()`) time.
1531 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1532 /// a.rotate_left(2);
1533 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1536 /// Rotating a subslice:
1539 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1540 /// a[1..5].rotate_left(1);
1541 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1543 #[stable(feature = "slice_rotate", since = "1.26.0")]
1544 pub fn rotate_left(&mut self, mid
: usize) {
1545 core_slice
::SliceExt
::rotate_left(self, mid
);
1548 /// Rotates the slice in-place such that the first `self.len() - k`
1549 /// elements of the slice move to the end while the last `k` elements move
1550 /// to the front. After calling `rotate_right`, the element previously at
1551 /// index `self.len() - k` will become the first element in the slice.
1555 /// This function will panic if `k` is greater than the length of the
1556 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1561 /// Takes linear (in `self.len()`) time.
1566 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1567 /// a.rotate_right(2);
1568 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1571 /// Rotate a subslice:
1574 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1575 /// a[1..5].rotate_right(1);
1576 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1578 #[stable(feature = "slice_rotate", since = "1.26.0")]
1579 pub fn rotate_right(&mut self, k
: usize) {
1580 core_slice
::SliceExt
::rotate_right(self, k
);
1583 /// Copies the elements from `src` into `self`.
1585 /// The length of `src` must be the same as `self`.
1587 /// If `src` implements `Copy`, it can be more performant to use
1588 /// [`copy_from_slice`].
1592 /// This function will panic if the two slices have different lengths.
1596 /// Cloning two elements from a slice into another:
1599 /// let src = [1, 2, 3, 4];
1600 /// let mut dst = [0, 0];
1602 /// dst.clone_from_slice(&src[2..]);
1604 /// assert_eq!(src, [1, 2, 3, 4]);
1605 /// assert_eq!(dst, [3, 4]);
1608 /// Rust enforces that there can only be one mutable reference with no
1609 /// immutable references to a particular piece of data in a particular
1610 /// scope. Because of this, attempting to use `clone_from_slice` on a
1611 /// single slice will result in a compile failure:
1614 /// let mut slice = [1, 2, 3, 4, 5];
1616 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1619 /// To work around this, we can use [`split_at_mut`] to create two distinct
1620 /// sub-slices from a slice:
1623 /// let mut slice = [1, 2, 3, 4, 5];
1626 /// let (left, right) = slice.split_at_mut(2);
1627 /// left.clone_from_slice(&right[1..]);
1630 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1633 /// [`copy_from_slice`]: #method.copy_from_slice
1634 /// [`split_at_mut`]: #method.split_at_mut
1635 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1636 pub fn clone_from_slice(&mut self, src
: &[T
]) where T
: Clone
{
1637 core_slice
::SliceExt
::clone_from_slice(self, src
)
1640 /// Copies all elements from `src` into `self`, using a memcpy.
1642 /// The length of `src` must be the same as `self`.
1644 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1648 /// This function will panic if the two slices have different lengths.
1652 /// Copying two elements from a slice into another:
1655 /// let src = [1, 2, 3, 4];
1656 /// let mut dst = [0, 0];
1658 /// dst.copy_from_slice(&src[2..]);
1660 /// assert_eq!(src, [1, 2, 3, 4]);
1661 /// assert_eq!(dst, [3, 4]);
1664 /// Rust enforces that there can only be one mutable reference with no
1665 /// immutable references to a particular piece of data in a particular
1666 /// scope. Because of this, attempting to use `copy_from_slice` on a
1667 /// single slice will result in a compile failure:
1670 /// let mut slice = [1, 2, 3, 4, 5];
1672 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1675 /// To work around this, we can use [`split_at_mut`] to create two distinct
1676 /// sub-slices from a slice:
1679 /// let mut slice = [1, 2, 3, 4, 5];
1682 /// let (left, right) = slice.split_at_mut(2);
1683 /// left.copy_from_slice(&right[1..]);
1686 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1689 /// [`clone_from_slice`]: #method.clone_from_slice
1690 /// [`split_at_mut`]: #method.split_at_mut
1691 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1692 pub fn copy_from_slice(&mut self, src
: &[T
]) where T
: Copy
{
1693 core_slice
::SliceExt
::copy_from_slice(self, src
)
1696 /// Swaps all elements in `self` with those in `other`.
1698 /// The length of `other` must be the same as `self`.
1702 /// This function will panic if the two slices have different lengths.
1706 /// Swapping two elements across slices:
1709 /// #![feature(swap_with_slice)]
1711 /// let mut slice1 = [0, 0];
1712 /// let mut slice2 = [1, 2, 3, 4];
1714 /// slice1.swap_with_slice(&mut slice2[2..]);
1716 /// assert_eq!(slice1, [3, 4]);
1717 /// assert_eq!(slice2, [1, 2, 0, 0]);
1720 /// Rust enforces that there can only be one mutable reference to a
1721 /// particular piece of data in a particular scope. Because of this,
1722 /// attempting to use `swap_with_slice` on a single slice will result in
1723 /// a compile failure:
1726 /// #![feature(swap_with_slice)]
1728 /// let mut slice = [1, 2, 3, 4, 5];
1729 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
1732 /// To work around this, we can use [`split_at_mut`] to create two distinct
1733 /// mutable sub-slices from a slice:
1736 /// #![feature(swap_with_slice)]
1738 /// let mut slice = [1, 2, 3, 4, 5];
1741 /// let (left, right) = slice.split_at_mut(2);
1742 /// left.swap_with_slice(&mut right[1..]);
1745 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
1748 /// [`split_at_mut`]: #method.split_at_mut
1749 #[unstable(feature = "swap_with_slice", issue = "44030")]
1750 pub fn swap_with_slice(&mut self, other
: &mut [T
]) {
1751 core_slice
::SliceExt
::swap_with_slice(self, other
)
1754 /// Copies `self` into a new `Vec`.
1759 /// let s = [10, 40, 30];
1760 /// let x = s.to_vec();
1761 /// // Here, `s` and `x` can be modified independently.
1763 #[rustc_conversion_suggestion]
1764 #[stable(feature = "rust1", since = "1.0.0")]
1766 pub fn to_vec(&self) -> Vec
<T
>
1769 // NB see hack module in this file
1773 /// Converts `self` into a vector without clones or allocation.
1775 /// The resulting vector can be converted back into a box via
1776 /// `Vec<T>`'s `into_boxed_slice` method.
1781 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1782 /// let x = s.into_vec();
1783 /// // `s` cannot be used anymore because it has been converted into `x`.
1785 /// assert_eq!(x, vec![10, 40, 30]);
1787 #[stable(feature = "rust1", since = "1.0.0")]
1789 pub fn into_vec(self: Box
<Self>) -> Vec
<T
> {
1790 // NB see hack module in this file
1791 hack
::into_vec(self)
1795 #[lang = "slice_u8"]
1798 /// Checks if all bytes in this slice are within the ASCII range.
1799 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1801 pub fn is_ascii(&self) -> bool
{
1802 self.iter().all(|b
| b
.is_ascii())
1805 /// Returns a vector containing a copy of this slice where each byte
1806 /// is mapped to its ASCII upper case equivalent.
1808 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1809 /// but non-ASCII letters are unchanged.
1811 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
1813 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
1814 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1816 pub fn to_ascii_uppercase(&self) -> Vec
<u8> {
1817 let mut me
= self.to_vec();
1818 me
.make_ascii_uppercase();
1822 /// Returns a vector containing a copy of this slice where each byte
1823 /// is mapped to its ASCII lower case equivalent.
1825 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1826 /// but non-ASCII letters are unchanged.
1828 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
1830 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
1831 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1833 pub fn to_ascii_lowercase(&self) -> Vec
<u8> {
1834 let mut me
= self.to_vec();
1835 me
.make_ascii_lowercase();
1839 /// Checks that two slices are an ASCII case-insensitive match.
1841 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1842 /// but without allocating and copying temporaries.
1843 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1845 pub fn eq_ignore_ascii_case(&self, other
: &[u8]) -> bool
{
1846 self.len() == other
.len() &&
1847 self.iter().zip(other
).all(|(a
, b
)| {
1848 a
.eq_ignore_ascii_case(b
)
1852 /// Converts this slice to its ASCII upper case equivalent in-place.
1854 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1855 /// but non-ASCII letters are unchanged.
1857 /// To return a new uppercased value without modifying the existing one, use
1858 /// [`to_ascii_uppercase`].
1860 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1861 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1863 pub fn make_ascii_uppercase(&mut self) {
1865 byte
.make_ascii_uppercase();
1869 /// Converts this slice to its ASCII lower case equivalent in-place.
1871 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1872 /// but non-ASCII letters are unchanged.
1874 /// To return a new lowercased value without modifying the existing one, use
1875 /// [`to_ascii_lowercase`].
1877 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1878 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1880 pub fn make_ascii_lowercase(&mut self) {
1882 byte
.make_ascii_lowercase();
1887 ////////////////////////////////////////////////////////////////////////////////
1888 // Extension traits for slices over specific kinds of data
1889 ////////////////////////////////////////////////////////////////////////////////
1890 #[unstable(feature = "slice_concat_ext",
1891 reason
= "trait should not have to exist",
1893 /// An extension trait for concatenating slices
1895 /// While this trait is unstable, the methods are stable. `SliceConcatExt` is
1896 /// included in the [standard library prelude], so you can use [`join()`] and
1897 /// [`concat()`] as if they existed on `[T]` itself.
1899 /// [standard library prelude]: ../../std/prelude/index.html
1900 /// [`join()`]: #tymethod.join
1901 /// [`concat()`]: #tymethod.concat
1902 pub trait SliceConcatExt
<T
: ?Sized
> {
1903 #[unstable(feature = "slice_concat_ext",
1904 reason
= "trait should not have to exist",
1906 /// The resulting type after concatenation
1909 /// Flattens a slice of `T` into a single value `Self::Output`.
1914 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1915 /// assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 fn concat(&self) -> Self::Output
;
1920 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1921 /// given separator between each.
1926 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1927 /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
1929 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1930 fn join(&self, sep
: &T
) -> Self::Output
;
1932 #[stable(feature = "rust1", since = "1.0.0")]
1933 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1934 fn connect(&self, sep
: &T
) -> Self::Output
;
1937 #[unstable(feature = "slice_concat_ext",
1938 reason
= "trait should not have to exist",
1940 impl<T
: Clone
, V
: Borrow
<[T
]>> SliceConcatExt
<T
> for [V
] {
1941 type Output
= Vec
<T
>;
1943 fn concat(&self) -> Vec
<T
> {
1944 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1945 let mut result
= Vec
::with_capacity(size
);
1947 result
.extend_from_slice(v
.borrow())
1952 fn join(&self, sep
: &T
) -> Vec
<T
> {
1953 let size
= self.iter().fold(0, |acc
, v
| acc
+ v
.borrow().len());
1954 let mut result
= Vec
::with_capacity(size
+ self.len());
1955 let mut first
= true;
1960 result
.push(sep
.clone())
1962 result
.extend_from_slice(v
.borrow())
1967 fn connect(&self, sep
: &T
) -> Vec
<T
> {
1972 ////////////////////////////////////////////////////////////////////////////////
1973 // Standard trait implementations for slices
1974 ////////////////////////////////////////////////////////////////////////////////
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl<T
> Borrow
<[T
]> for Vec
<T
> {
1978 fn borrow(&self) -> &[T
] {
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<T
> BorrowMut
<[T
]> for Vec
<T
> {
1985 fn borrow_mut(&mut self) -> &mut [T
] {
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl<T
: Clone
> ToOwned
for [T
] {
1992 type Owned
= Vec
<T
>;
1994 fn to_owned(&self) -> Vec
<T
> {
1999 fn to_owned(&self) -> Vec
<T
> {
2003 fn clone_into(&self, target
: &mut Vec
<T
>) {
2004 // drop anything in target that will not be overwritten
2005 target
.truncate(self.len());
2006 let len
= target
.len();
2008 // reuse the contained values' allocations/resources.
2009 target
.clone_from_slice(&self[..len
]);
2011 // target.len <= self.len due to the truncate above, so the
2012 // slice here is always in-bounds.
2013 target
.extend_from_slice(&self[len
..]);
2017 ////////////////////////////////////////////////////////////////////////////////
2019 ////////////////////////////////////////////////////////////////////////////////
2021 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
2023 /// This is the integral subroutine of insertion sort.
2024 fn insert_head
<T
, F
>(v
: &mut [T
], is_less
: &mut F
)
2025 where F
: FnMut(&T
, &T
) -> bool
2027 if v
.len() >= 2 && is_less(&v
[1], &v
[0]) {
2029 // There are three ways to implement insertion here:
2031 // 1. Swap adjacent elements until the first one gets to its final destination.
2032 // However, this way we copy data around more than is necessary. If elements are big
2033 // structures (costly to copy), this method will be slow.
2035 // 2. Iterate until the right place for the first element is found. Then shift the
2036 // elements succeeding it to make room for it and finally place it into the
2037 // remaining hole. This is a good method.
2039 // 3. Copy the first element into a temporary variable. Iterate until the right place
2040 // for it is found. As we go along, copy every traversed element into the slot
2041 // preceding it. Finally, copy data from the temporary variable into the remaining
2042 // hole. This method is very good. Benchmarks demonstrated slightly better
2043 // performance than with the 2nd method.
2045 // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
2046 let mut tmp
= mem
::ManuallyDrop
::new(ptr
::read(&v
[0]));
2048 // Intermediate state of the insertion process is always tracked by `hole`, which
2049 // serves two purposes:
2050 // 1. Protects integrity of `v` from panics in `is_less`.
2051 // 2. Fills the remaining hole in `v` in the end.
2055 // If `is_less` panics at any point during the process, `hole` will get dropped and
2056 // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
2057 // initially held exactly once.
2058 let mut hole
= InsertionHole
{
2062 ptr
::copy_nonoverlapping(&v
[1], &mut v
[0], 1);
2064 for i
in 2..v
.len() {
2065 if !is_less(&v
[i
], &*tmp
) {
2068 ptr
::copy_nonoverlapping(&v
[i
], &mut v
[i
- 1], 1);
2069 hole
.dest
= &mut v
[i
];
2071 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
2075 // When dropped, copies from `src` into `dest`.
2076 struct InsertionHole
<T
> {
2081 impl<T
> Drop
for InsertionHole
<T
> {
2082 fn drop(&mut self) {
2083 unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
2088 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
2089 /// stores the result into `v[..]`.
2093 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
2094 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
2095 unsafe fn merge
<T
, F
>(v
: &mut [T
], mid
: usize, buf
: *mut T
, is_less
: &mut F
)
2096 where F
: FnMut(&T
, &T
) -> bool
2099 let v
= v
.as_mut_ptr();
2100 let v_mid
= v
.offset(mid
as isize);
2101 let v_end
= v
.offset(len
as isize);
2103 // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
2104 // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
2105 // copying the lesser (or greater) one into `v`.
2107 // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
2108 // consumed first, then we must copy whatever is left of the shorter run into the remaining
2111 // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
2112 // 1. Protects integrity of `v` from panics in `is_less`.
2113 // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
2117 // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
2118 // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
2119 // object it initially held exactly once.
2122 if mid
<= len
- mid
{
2123 // The left run is shorter.
2124 ptr
::copy_nonoverlapping(v
, buf
, mid
);
2127 end
: buf
.offset(mid
as isize),
2131 // Initially, these pointers point to the beginnings of their arrays.
2132 let left
= &mut hole
.start
;
2133 let mut right
= v_mid
;
2134 let out
= &mut hole
.dest
;
2136 while *left
< hole
.end
&& right
< v_end
{
2137 // Consume the lesser side.
2138 // If equal, prefer the left run to maintain stability.
2139 let to_copy
= if is_less(&*right
, &**left
) {
2140 get_and_increment(&mut right
)
2142 get_and_increment(left
)
2144 ptr
::copy_nonoverlapping(to_copy
, get_and_increment(out
), 1);
2147 // The right run is shorter.
2148 ptr
::copy_nonoverlapping(v_mid
, buf
, len
- mid
);
2151 end
: buf
.offset((len
- mid
) as isize),
2155 // Initially, these pointers point past the ends of their arrays.
2156 let left
= &mut hole
.dest
;
2157 let right
= &mut hole
.end
;
2158 let mut out
= v_end
;
2160 while v
< *left
&& buf
< *right
{
2161 // Consume the greater side.
2162 // If equal, prefer the right run to maintain stability.
2163 let to_copy
= if is_less(&*right
.offset(-1), &*left
.offset(-1)) {
2164 decrement_and_get(left
)
2166 decrement_and_get(right
)
2168 ptr
::copy_nonoverlapping(to_copy
, decrement_and_get(&mut out
), 1);
2171 // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
2172 // it will now be copied into the hole in `v`.
2174 unsafe fn get_and_increment
<T
>(ptr
: &mut *mut T
) -> *mut T
{
2176 *ptr
= ptr
.offset(1);
2180 unsafe fn decrement_and_get
<T
>(ptr
: &mut *mut T
) -> *mut T
{
2181 *ptr
= ptr
.offset(-1);
2185 // When dropped, copies the range `start..end` into `dest..`.
2186 struct MergeHole
<T
> {
2192 impl<T
> Drop
for MergeHole
<T
> {
2193 fn drop(&mut self) {
2194 // `T` is not a zero-sized type, so it's okay to divide by its size.
2195 let len
= (self.end
as usize - self.start
as usize) / mem
::size_of
::<T
>();
2196 unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
2201 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
2202 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
2204 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
2205 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
2206 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
2209 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
2210 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
2212 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
2213 fn merge_sort
<T
, F
>(v
: &mut [T
], mut is_less
: F
)
2214 where F
: FnMut(&T
, &T
) -> bool
2216 // Slices of up to this length get sorted using insertion sort.
2217 const MAX_INSERTION
: usize = 20;
2218 // Very short runs are extended using insertion sort to span at least this many elements.
2219 const MIN_RUN
: usize = 10;
2221 // Sorting has no meaningful behavior on zero-sized types.
2222 if size_of
::<T
>() == 0 {
2228 // Short arrays get sorted in-place via insertion sort to avoid allocations.
2229 if len
<= MAX_INSERTION
{
2231 for i
in (0..len
-1).rev() {
2232 insert_head(&mut v
[i
..], &mut is_less
);
2238 // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
2239 // shallow copies of the contents of `v` without risking the dtors running on copies if
2240 // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
2241 // which will always have length at most `len / 2`.
2242 let mut buf
= Vec
::with_capacity(len
/ 2);
2244 // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
2245 // strange decision, but consider the fact that merges more often go in the opposite direction
2246 // (forwards). According to benchmarks, merging forwards is slightly faster than merging
2247 // backwards. To conclude, identifying runs by traversing backwards improves performance.
2248 let mut runs
= vec
![];
2251 // Find the next natural run, and reverse it if it's strictly descending.
2252 let mut start
= end
- 1;
2256 if is_less(v
.get_unchecked(start
+ 1), v
.get_unchecked(start
)) {
2257 while start
> 0 && is_less(v
.get_unchecked(start
),
2258 v
.get_unchecked(start
- 1)) {
2261 v
[start
..end
].reverse();
2263 while start
> 0 && !is_less(v
.get_unchecked(start
),
2264 v
.get_unchecked(start
- 1)) {
2271 // Insert some more elements into the run if it's too short. Insertion sort is faster than
2272 // merge sort on short sequences, so this significantly improves performance.
2273 while start
> 0 && end
- start
< MIN_RUN
{
2275 insert_head(&mut v
[start
..end
], &mut is_less
);
2278 // Push this run onto the stack.
2285 // Merge some pairs of adjacent runs to satisfy the invariants.
2286 while let Some(r
) = collapse(&runs
) {
2287 let left
= runs
[r
+ 1];
2288 let right
= runs
[r
];
2290 merge(&mut v
[left
.start
.. right
.start
+ right
.len
], left
.len
, buf
.as_mut_ptr(),
2295 len
: left
.len
+ right
.len
,
2301 // Finally, exactly one run must remain in the stack.
2302 debug_assert
!(runs
.len() == 1 && runs
[0].start
== 0 && runs
[0].len
== len
);
2304 // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
2305 // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
2306 // algorithm should continue building a new run instead, `None` is returned.
2308 // TimSort is infamous for its buggy implementations, as described here:
2309 // http://envisage-project.eu/timsort-specification-and-verification/
2311 // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
2312 // Enforcing them on just top three is not sufficient to ensure that the invariants will still
2313 // hold for *all* runs in the stack.
2315 // This function correctly checks invariants for the top four runs. Additionally, if the top
2316 // run starts at index 0, it will always demand a merge operation until the stack is fully
2317 // collapsed, in order to complete the sort.
2319 fn collapse(runs
: &[Run
]) -> Option
<usize> {
2321 if n
>= 2 && (runs
[n
- 1].start
== 0 ||
2322 runs
[n
- 2].len
<= runs
[n
- 1].len
||
2323 (n
>= 3 && runs
[n
- 3].len
<= runs
[n
- 2].len
+ runs
[n
- 1].len
) ||
2324 (n
>= 4 && runs
[n
- 4].len
<= runs
[n
- 3].len
+ runs
[n
- 2].len
)) {
2325 if n
>= 3 && runs
[n
- 3].len
< runs
[n
- 1].len
{
2335 #[derive(Clone, Copy)]