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 #[unstable(feature = "slice_rsplit", issue = "41020")]
119 pub use core::slice::{RSplit, RSplitMut};
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
122 #[unstable(feature = "slice_get_slice", issue = "35729")]
123 pub use core::slice::SliceIndex;
125 ////////////////////////////////////////////////////////////////////////////////
126 // Basic slice extension methods
127 ////////////////////////////////////////////////////////////////////////////////
129 // HACK(japaric) needed for the implementation of `vec!` macro during testing
130 // NB see the hack module in this file for more details
132 pub use self::hack::into_vec;
134 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
135 // NB see the hack module in this file for more details
137 pub use self::hack::to_vec;
139 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
140 // functions are actually methods that are in `impl [T]` but not in
141 // `core::slice::SliceExt` - we need to supply these functions for the
142 // `test_permutations` test
144 use alloc::boxed::Box;
148 use string::ToString;
151 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
153 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
160 pub fn to_vec<T>(s: &[T]) -> Vec<T>
163 let mut vector = Vec::with_capacity(s.len());
164 vector.extend_from_slice(s);
172 /// Returns the number of elements in the slice.
177 /// let a = [1, 2, 3];
178 /// assert_eq!(a.len(), 3);
180 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn len(&self) -> usize {
183 core_slice::SliceExt::len(self)
186 /// Returns `true` if the slice has a length of 0.
191 /// let a = [1, 2, 3];
192 /// assert!(!a.is_empty());
194 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn is_empty(&self) -> bool {
197 core_slice::SliceExt::is_empty(self)
200 /// Returns the first element of the slice, or `None` if it is empty.
205 /// let v = [10, 40, 30];
206 /// assert_eq!(Some(&10), v.first());
208 /// let w: &[i32] = &[];
209 /// assert_eq!(None, w.first());
211 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn first(&self) -> Option<&T> {
214 core_slice::SliceExt::first(self)
217 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
222 /// let x = &mut [0, 1, 2];
224 /// if let Some(first) = x.first_mut() {
227 /// assert_eq!(x, &[5, 1, 2]);
229 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn first_mut(&mut self) -> Option<&mut T> {
232 core_slice::SliceExt::first_mut(self)
235 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
240 /// let x = &[0, 1, 2];
242 /// if let Some((first, elements)) = x.split_first() {
243 /// assert_eq!(first, &0);
244 /// assert_eq!(elements, &[1, 2]);
247 #[stable(feature = "slice_splits", since = "1.5.0")]
249 pub fn split_first(&self) -> Option<(&T, &[T])> {
250 core_slice::SliceExt::split_first(self)
253 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
258 /// let x = &mut [0, 1, 2];
260 /// if let Some((first, elements)) = x.split_first_mut() {
265 /// assert_eq!(x, &[3, 4, 5]);
267 #[stable(feature = "slice_splits", since = "1.5.0")]
269 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
270 core_slice::SliceExt::split_first_mut(self)
273 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
278 /// let x = &[0, 1, 2];
280 /// if let Some((last, elements)) = x.split_last() {
281 /// assert_eq!(last, &2);
282 /// assert_eq!(elements, &[0, 1]);
285 #[stable(feature = "slice_splits", since = "1.5.0")]
287 pub fn split_last(&self) -> Option<(&T, &[T])> {
288 core_slice::SliceExt::split_last(self)
292 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
297 /// let x = &mut [0, 1, 2];
299 /// if let Some((last, elements)) = x.split_last_mut() {
304 /// assert_eq!(x, &[4, 5, 3]);
306 #[stable(feature = "slice_splits", since = "1.5.0")]
308 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
309 core_slice::SliceExt::split_last_mut(self)
312 /// Returns the last element of the slice, or `None` if it is empty.
317 /// let v = [10, 40, 30];
318 /// assert_eq!(Some(&30), v.last());
320 /// let w: &[i32] = &[];
321 /// assert_eq!(None, w.last());
323 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn last(&self) -> Option<&T> {
326 core_slice::SliceExt::last(self)
329 /// Returns a mutable pointer to the last item in the slice.
334 /// let x = &mut [0, 1, 2];
336 /// if let Some(last) = x.last_mut() {
339 /// assert_eq!(x, &[0, 1, 10]);
341 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn last_mut(&mut self) -> Option<&mut T> {
344 core_slice::SliceExt::last_mut(self)
347 /// Returns a reference to an element or subslice depending on the type of
350 /// - If given a position, returns a reference to the element at that
351 /// position or `None` if out of bounds.
352 /// - If given a range, returns the subslice corresponding to that range,
353 /// or `None` if out of bounds.
358 /// let v = [10, 40, 30];
359 /// assert_eq!(Some(&40), v.get(1));
360 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
361 /// assert_eq!(None, v.get(3));
362 /// assert_eq!(None, v.get(0..4));
364 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn get<I>(&self, index: I) -> Option<&I::Output>
367 where I: SliceIndex<Self>
369 core_slice::SliceExt::get(self, index)
372 /// Returns a mutable reference to an element or subslice depending on the
373 /// type of index (see [`get`]) or `None` if the index is out of bounds.
375 /// [`get`]: #method.get
380 /// let x = &mut [0, 1, 2];
382 /// if let Some(elem) = x.get_mut(1) {
385 /// assert_eq!(x, &[0, 42, 2]);
387 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
390 where I: SliceIndex<Self>
392 core_slice::SliceExt::get_mut(self, index)
395 /// Returns a reference to an element or subslice, without doing bounds
398 /// This is generally not recommended, use with caution! For a safe
399 /// alternative see [`get`].
401 /// [`get`]: #method.get
406 /// let x = &[1, 2, 4];
409 /// assert_eq!(x.get_unchecked(1), &2);
412 #[stable(feature = "rust1", since = "1.0.0")]
414 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
415 where I: SliceIndex<Self>
417 core_slice::SliceExt::get_unchecked(self, index)
420 /// Returns a mutable reference to an element or subslice, without doing
423 /// This is generally not recommended, use with caution! For a safe
424 /// alternative see [`get_mut`].
426 /// [`get_mut`]: #method.get_mut
431 /// let x = &mut [1, 2, 4];
434 /// let elem = x.get_unchecked_mut(1);
437 /// assert_eq!(x, &[1, 13, 4]);
439 #[stable(feature = "rust1", since = "1.0.0")]
441 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
442 where I: SliceIndex<Self>
444 core_slice::SliceExt::get_unchecked_mut(self, index)
447 /// Returns a raw pointer to the slice's buffer.
449 /// The caller must ensure that the slice outlives the pointer this
450 /// function returns, or else it will end up pointing to garbage.
452 /// Modifying the container referenced by this slice may cause its buffer
453 /// to be reallocated, which would also make any pointers to it invalid.
458 /// let x = &[1, 2, 4];
459 /// let x_ptr = x.as_ptr();
462 /// for i in 0..x.len() {
463 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
467 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn as_ptr(&self) -> *const T {
470 core_slice::SliceExt::as_ptr(self)
473 /// Returns an unsafe mutable pointer to the slice's buffer.
475 /// The caller must ensure that the slice outlives the pointer this
476 /// function returns, or else it will end up pointing to garbage.
478 /// Modifying the container referenced by this slice may cause its buffer
479 /// to be reallocated, which would also make any pointers to it invalid.
484 /// let x = &mut [1, 2, 4];
485 /// let x_ptr = x.as_mut_ptr();
488 /// for i in 0..x.len() {
489 /// *x_ptr.offset(i as isize) += 2;
492 /// assert_eq!(x, &[3, 4, 6]);
494 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn as_mut_ptr(&mut self) -> *mut T {
497 core_slice::SliceExt::as_mut_ptr(self)
500 /// Swaps two elements in the slice.
504 /// * a - The index of the first element
505 /// * b - The index of the second element
509 /// Panics if `a` or `b` are out of bounds.
514 /// let mut v = ["a", "b", "c", "d"];
516 /// assert!(v == ["a", "d", "c", "b"]);
518 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn swap(&mut self, a: usize, b: usize) {
521 core_slice::SliceExt::swap(self, a, b)
524 /// Reverses the order of elements in the slice, in place.
529 /// let mut v = [1, 2, 3];
531 /// assert!(v == [3, 2, 1]);
533 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn reverse(&mut self) {
536 core_slice::SliceExt::reverse(self)
539 /// Returns an iterator over the slice.
544 /// let x = &[1, 2, 4];
545 /// let mut iterator = x.iter();
547 /// assert_eq!(iterator.next(), Some(&1));
548 /// assert_eq!(iterator.next(), Some(&2));
549 /// assert_eq!(iterator.next(), Some(&4));
550 /// assert_eq!(iterator.next(), None);
552 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn iter(&self) -> Iter<T> {
555 core_slice::SliceExt::iter(self)
558 /// Returns an iterator that allows modifying each value.
563 /// let x = &mut [1, 2, 4];
564 /// for elem in x.iter_mut() {
567 /// assert_eq!(x, &[3, 4, 6]);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn iter_mut(&mut self) -> IterMut<T> {
572 core_slice::SliceExt::iter_mut(self)
575 /// Returns an iterator over all contiguous windows of length
576 /// `size`. The windows overlap. If the slice is shorter than
577 /// `size`, the iterator returns no values.
581 /// Panics if `size` is 0.
586 /// let slice = ['r', 'u', 's', 't'];
587 /// let mut iter = slice.windows(2);
588 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
589 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
590 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
591 /// assert!(iter.next().is_none());
594 /// If the slice is shorter than `size`:
597 /// let slice = ['f', 'o', 'o'];
598 /// let mut iter = slice.windows(4);
599 /// assert!(iter.next().is_none());
601 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn windows(&self, size: usize) -> Windows<T> {
604 core_slice::SliceExt::windows(self, size)
607 /// Returns an iterator over `size` elements of the slice at a
608 /// time. The chunks are slices and do not overlap. If `size` does
609 /// not divide the length of the slice, then the last chunk will
610 /// not have length `size`.
614 /// Panics if `size` is 0.
619 /// let slice = ['l', 'o', 'r', 'e', 'm'];
620 /// let mut iter = slice.chunks(2);
621 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
622 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
623 /// assert_eq!(iter.next().unwrap(), &['m']);
624 /// assert!(iter.next().is_none());
626 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn chunks(&self, size: usize) -> Chunks<T> {
629 core_slice::SliceExt::chunks(self, size)
632 /// Returns an iterator over `chunk_size` elements of the slice at a time.
633 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
634 /// not divide the length of the slice, then the last chunk will not
635 /// have length `chunk_size`.
639 /// Panics if `chunk_size` is 0.
644 /// let v = &mut [0, 0, 0, 0, 0];
645 /// let mut count = 1;
647 /// for chunk in v.chunks_mut(2) {
648 /// for elem in chunk.iter_mut() {
653 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
655 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
658 core_slice::SliceExt::chunks_mut(self, chunk_size)
661 /// Divides one slice into two at an index.
663 /// The first will contain all indices from `[0, mid)` (excluding
664 /// the index `mid` itself) and the second will contain all
665 /// indices from `[mid, len)` (excluding the index `len` itself).
669 /// Panics if `mid > len`.
674 /// let v = [10, 40, 30, 20, 50];
675 /// let (v1, v2) = v.split_at(2);
676 /// assert_eq!([10, 40], v1);
677 /// assert_eq!([30, 20, 50], v2);
679 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
682 core_slice::SliceExt::split_at(self, mid)
685 /// Divides one `&mut` into two at an index.
687 /// The first will contain all indices from `[0, mid)` (excluding
688 /// the index `mid` itself) and the second will contain all
689 /// indices from `[mid, len)` (excluding the index `len` itself).
693 /// Panics if `mid > len`.
698 /// let mut v = [1, 2, 3, 4, 5, 6];
700 /// // scoped to restrict the lifetime of the borrows
702 /// let (left, right) = v.split_at_mut(0);
703 /// assert!(left == []);
704 /// assert!(right == [1, 2, 3, 4, 5, 6]);
708 /// let (left, right) = v.split_at_mut(2);
709 /// assert!(left == [1, 2]);
710 /// assert!(right == [3, 4, 5, 6]);
714 /// let (left, right) = v.split_at_mut(6);
715 /// assert!(left == [1, 2, 3, 4, 5, 6]);
716 /// assert!(right == []);
719 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
722 core_slice::SliceExt::split_at_mut(self, mid)
725 /// Returns an iterator over subslices separated by elements that match
726 /// `pred`. The matched element is not contained in the subslices.
731 /// let slice = [10, 40, 33, 20];
732 /// let mut iter = slice.split(|num| num % 3 == 0);
734 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
735 /// assert_eq!(iter.next().unwrap(), &[20]);
736 /// assert!(iter.next().is_none());
739 /// If the first element is matched, an empty slice will be the first item
740 /// returned by the iterator. Similarly, if the last element in the slice
741 /// is matched, an empty slice will be the last item returned by the
745 /// let slice = [10, 40, 33];
746 /// let mut iter = slice.split(|num| num % 3 == 0);
748 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
749 /// assert_eq!(iter.next().unwrap(), &[]);
750 /// assert!(iter.next().is_none());
753 /// If two matched elements are directly adjacent, an empty slice will be
754 /// present between them:
757 /// let slice = [10, 6, 33, 20];
758 /// let mut iter = slice.split(|num| num % 3 == 0);
760 /// assert_eq!(iter.next().unwrap(), &[10]);
761 /// assert_eq!(iter.next().unwrap(), &[]);
762 /// assert_eq!(iter.next().unwrap(), &[20]);
763 /// assert!(iter.next().is_none());
765 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn split<F>(&self, pred: F) -> Split<T, F>
768 where F: FnMut(&T) -> bool
770 core_slice::SliceExt::split(self, pred)
773 /// Returns an iterator over mutable subslices separated by elements that
774 /// match `pred`. The matched element is not contained in the subslices.
779 /// let mut v = [10, 40, 30, 20, 60, 50];
781 /// for group in v.split_mut(|num| *num % 3 == 0) {
784 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
786 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
789 where F: FnMut(&T) -> bool
791 core_slice::SliceExt::split_mut(self, pred)
794 /// Returns an iterator over subslices separated by elements that match
795 /// `pred`, starting at the end of the slice and working backwards.
796 /// The matched element is not contained in the subslices.
801 /// #![feature(slice_rsplit)]
803 /// let slice = [11, 22, 33, 0, 44, 55];
804 /// let mut iter = slice.rsplit(|num| *num == 0);
806 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
807 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
808 /// assert_eq!(iter.next(), None);
811 /// As with `split()`, if the first or last element is matched, an empty
812 /// slice will be the first (or last) item returned by the iterator.
815 /// #![feature(slice_rsplit)]
817 /// let v = &[0, 1, 1, 2, 3, 5, 8];
818 /// let mut it = v.rsplit(|n| *n % 2 == 0);
819 /// assert_eq!(it.next().unwrap(), &[]);
820 /// assert_eq!(it.next().unwrap(), &[3, 5]);
821 /// assert_eq!(it.next().unwrap(), &[1, 1]);
822 /// assert_eq!(it.next().unwrap(), &[]);
823 /// assert_eq!(it.next(), None);
825 #[unstable(feature = "slice_rsplit", issue = "41020")]
827 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
828 where F: FnMut(&T) -> bool
830 core_slice::SliceExt::rsplit(self, pred)
833 /// Returns an iterator over mutable subslices separated by elements that
834 /// match `pred`, starting at the end of the slice and working
835 /// backwards. The matched element is not contained in the subslices.
840 /// #![feature(slice_rsplit)]
842 /// let mut v = [100, 400, 300, 200, 600, 500];
844 /// let mut count = 0;
845 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
847 /// group[0] = count;
849 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
852 #[unstable(feature = "slice_rsplit", issue = "41020")]
854 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
855 where F: FnMut(&T) -> bool
857 core_slice::SliceExt::rsplit_mut(self, pred)
860 /// Returns an iterator over subslices separated by elements that match
861 /// `pred`, limited to returning at most `n` items. The matched element is
862 /// not contained in the subslices.
864 /// The last element returned, if any, will contain the remainder of the
869 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
873 /// let v = [10, 40, 30, 20, 60, 50];
875 /// for group in v.splitn(2, |num| *num % 3 == 0) {
876 /// println!("{:?}", group);
879 #[stable(feature = "rust1", since = "1.0.0")]
881 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
882 where F: FnMut(&T) -> bool
884 core_slice::SliceExt::splitn(self, n, pred)
887 /// Returns an iterator over subslices separated by elements that match
888 /// `pred`, limited to returning at most `n` items. The matched element is
889 /// not contained in the subslices.
891 /// The last element returned, if any, will contain the remainder of the
897 /// let mut v = [10, 40, 30, 20, 60, 50];
899 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
902 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
904 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
907 where F: FnMut(&T) -> bool
909 core_slice::SliceExt::splitn_mut(self, n, pred)
912 /// Returns an iterator over subslices separated by elements that match
913 /// `pred` limited to returning at most `n` items. This starts at the end of
914 /// the slice and works backwards. The matched element is not contained in
917 /// The last element returned, if any, will contain the remainder of the
922 /// Print the slice split once, starting from the end, by numbers divisible
923 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
926 /// let v = [10, 40, 30, 20, 60, 50];
928 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
929 /// println!("{:?}", group);
932 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
935 where F: FnMut(&T) -> bool
937 core_slice::SliceExt::rsplitn(self, n, pred)
940 /// Returns an iterator over subslices separated by elements that match
941 /// `pred` limited to returning at most `n` items. This starts at the end of
942 /// the slice and works backwards. The matched element is not contained in
945 /// The last element returned, if any, will contain the remainder of the
951 /// let mut s = [10, 40, 30, 20, 60, 50];
953 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
956 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
958 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
961 where F: FnMut(&T) -> bool
963 core_slice::SliceExt::rsplitn_mut(self, n, pred)
966 /// Returns `true` if the slice contains an element with the given value.
971 /// let v = [10, 40, 30];
972 /// assert!(v.contains(&30));
973 /// assert!(!v.contains(&50));
975 #[stable(feature = "rust1", since = "1.0.0")]
976 pub fn contains(&self, x: &T) -> bool
979 core_slice::SliceExt::contains(self, x)
982 /// Returns `true` if `needle` is a prefix of the slice.
987 /// let v = [10, 40, 30];
988 /// assert!(v.starts_with(&[10]));
989 /// assert!(v.starts_with(&[10, 40]));
990 /// assert!(!v.starts_with(&[50]));
991 /// assert!(!v.starts_with(&[10, 50]));
994 /// Always returns `true` if `needle` is an empty slice:
997 /// let v = &[10, 40, 30];
998 /// assert!(v.starts_with(&[]));
999 /// let v: &[u8] = &[];
1000 /// assert!(v.starts_with(&[]));
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn starts_with(&self, needle: &[T]) -> bool
1006 core_slice::SliceExt::starts_with(self, needle)
1009 /// Returns `true` if `needle` is a suffix of the slice.
1014 /// let v = [10, 40, 30];
1015 /// assert!(v.ends_with(&[30]));
1016 /// assert!(v.ends_with(&[40, 30]));
1017 /// assert!(!v.ends_with(&[50]));
1018 /// assert!(!v.ends_with(&[50, 30]));
1021 /// Always returns `true` if `needle` is an empty slice:
1024 /// let v = &[10, 40, 30];
1025 /// assert!(v.ends_with(&[]));
1026 /// let v: &[u8] = &[];
1027 /// assert!(v.ends_with(&[]));
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn ends_with(&self, needle: &[T]) -> bool
1033 core_slice::SliceExt::ends_with(self, needle)
1036 /// Binary searches this sorted slice for a given element.
1038 /// If the value is found then `Ok` is returned, containing the
1039 /// index of the matching element; if the value is not found then
1040 /// `Err` is returned, containing the index where a matching
1041 /// element could be inserted while maintaining sorted order.
1045 /// Looks up a series of four elements. The first is found, with a
1046 /// uniquely determined position; the second and third are not
1047 /// found; the fourth could match any position in `[1, 4]`.
1050 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1052 /// assert_eq!(s.binary_search(&13), Ok(9));
1053 /// assert_eq!(s.binary_search(&4), Err(7));
1054 /// assert_eq!(s.binary_search(&100), Err(13));
1055 /// let r = s.binary_search(&1);
1056 /// assert!(match r { Ok(1...4) => true, _ => false, });
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1062 core_slice::SliceExt::binary_search(self, x)
1065 /// Binary searches this sorted slice with a comparator function.
1067 /// The comparator function should implement an order consistent
1068 /// with the sort order of the underlying slice, returning an
1069 /// order code that indicates whether its argument is `Less`,
1070 /// `Equal` or `Greater` the desired target.
1072 /// If a matching value is found then returns `Ok`, containing
1073 /// the index for the matched element; if no match is found then
1074 /// `Err` is returned, containing the index where a matching
1075 /// element could be inserted while maintaining sorted order.
1079 /// Looks up a series of four elements. The first is found, with a
1080 /// uniquely determined position; the second and third are not
1081 /// found; the fourth could match any position in `[1, 4]`.
1084 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1087 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1089 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1091 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1093 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1094 /// assert!(match r { Ok(1...4) => true, _ => false, });
1096 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1099 where F: FnMut(&'a T) -> Ordering
1101 core_slice::SliceExt::binary_search_by(self, f)
1104 /// Binary searches this sorted slice with a key extraction function.
1106 /// Assumes that the slice is sorted by the key, for instance with
1107 /// [`sort_by_key`] using the same key extraction function.
1109 /// If a matching value is found then returns `Ok`, containing the
1110 /// index for the matched element; if no match is found then `Err`
1111 /// is returned, containing the index where a matching element could
1112 /// be inserted while maintaining sorted order.
1114 /// [`sort_by_key`]: #method.sort_by_key
1118 /// Looks up a series of four elements in a slice of pairs sorted by
1119 /// their second elements. The first is found, with a uniquely
1120 /// determined position; the second and third are not found; the
1121 /// fourth could match any position in `[1, 4]`.
1124 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1125 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1126 /// (1, 21), (2, 34), (4, 55)];
1128 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1129 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1130 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1131 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1132 /// assert!(match r { Ok(1...4) => true, _ => false, });
1134 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1136 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1137 where F: FnMut(&'a T) -> B,
1140 core_slice::SliceExt::binary_search_by_key(self, b, f)
1143 /// Sorts the slice.
1145 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1147 /// # Current implementation
1149 /// The current algorithm is an adaptive, iterative merge sort inspired by
1150 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1151 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1152 /// two or more sorted sequences concatenated one after another.
1154 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1155 /// non-allocating insertion sort is used instead.
1160 /// let mut v = [-5, 4, 1, -3, 2];
1163 /// assert!(v == [-5, -3, 1, 2, 4]);
1165 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub fn sort(&mut self)
1170 merge_sort(self, |a, b| a.lt(b));
1173 /// Sorts the slice with a comparator function.
1175 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1177 /// # Current implementation
1179 /// The current algorithm is an adaptive, iterative merge sort inspired by
1180 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1181 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1182 /// two or more sorted sequences concatenated one after another.
1184 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1185 /// non-allocating insertion sort is used instead.
1190 /// let mut v = [5, 4, 1, 3, 2];
1191 /// v.sort_by(|a, b| a.cmp(b));
1192 /// assert!(v == [1, 2, 3, 4, 5]);
1194 /// // reverse sorting
1195 /// v.sort_by(|a, b| b.cmp(a));
1196 /// assert!(v == [5, 4, 3, 2, 1]);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1200 pub fn sort_by<F>(&mut self, mut compare: F)
1201 where F: FnMut(&T, &T) -> Ordering
1203 merge_sort(self, |a, b| compare(a, b) == Less);
1206 /// Sorts the slice with a key extraction function.
1208 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1210 /// # Current implementation
1212 /// The current algorithm is an adaptive, iterative merge sort inspired by
1213 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1214 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1215 /// two or more sorted sequences concatenated one after another.
1217 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1218 /// non-allocating insertion sort is used instead.
1223 /// let mut v = [-5i32, 4, 1, -3, 2];
1225 /// v.sort_by_key(|k| k.abs());
1226 /// assert!(v == [1, 2, -3, 4, -5]);
1228 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1230 pub fn sort_by_key<B, F>(&mut self, mut f: F)
1231 where F: FnMut(&T) -> B, B: Ord
1233 merge_sort(self, |a, b| f(a).lt(&f(b)));
1236 /// Sorts the slice, but may not preserve the order of equal elements.
1238 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1239 /// and `O(n log n)` worst-case.
1241 /// # Current implementation
1243 /// The current algorithm is based on Orson Peters' [pattern-defeating quicksort][pdqsort],
1244 /// which is a quicksort variant designed to be very fast on certain kinds of patterns,
1245 /// sometimes achieving linear time. It is randomized but deterministic, and falls back to
1246 /// heapsort on degenerate inputs.
1248 /// It is generally faster than stable sorting, except in a few special cases, e.g. when the
1249 /// slice consists of several concatenated sorted sequences.
1254 /// #![feature(sort_unstable)]
1256 /// let mut v = [-5, 4, 1, -3, 2];
1258 /// v.sort_unstable();
1259 /// assert!(v == [-5, -3, 1, 2, 4]);
1262 /// [pdqsort]: https://github.com/orlp/pdqsort
1263 // FIXME #40585: Mention `sort_unstable` in the documentation for `sort`.
1264 #[unstable(feature = "sort_unstable", issue = "40585")]
1266 pub fn sort_unstable(&mut self)
1269 core_slice::SliceExt::sort_unstable(self);
1272 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1275 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1276 /// and `O(n log n)` worst-case.
1278 /// # Current implementation
1280 /// The current algorithm is based on Orson Peters' [pattern-defeating quicksort][pdqsort],
1281 /// which is a quicksort variant designed to be very fast on certain kinds of patterns,
1282 /// sometimes achieving linear time. It is randomized but deterministic, and falls back to
1283 /// heapsort on degenerate inputs.
1285 /// It is generally faster than stable sorting, except in a few special cases, e.g. when the
1286 /// slice consists of several concatenated sorted sequences.
1291 /// #![feature(sort_unstable)]
1293 /// let mut v = [5, 4, 1, 3, 2];
1294 /// v.sort_unstable_by(|a, b| a.cmp(b));
1295 /// assert!(v == [1, 2, 3, 4, 5]);
1297 /// // reverse sorting
1298 /// v.sort_unstable_by(|a, b| b.cmp(a));
1299 /// assert!(v == [5, 4, 3, 2, 1]);
1302 /// [pdqsort]: https://github.com/orlp/pdqsort
1303 // FIXME #40585: Mention `sort_unstable_by` in the documentation for `sort_by`.
1304 #[unstable(feature = "sort_unstable", issue = "40585")]
1306 pub fn sort_unstable_by<F>(&mut self, compare: F)
1307 where F: FnMut(&T, &T) -> Ordering
1309 core_slice::SliceExt::sort_unstable_by(self, compare);
1312 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1315 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1316 /// and `O(n log n)` worst-case.
1318 /// # Current implementation
1320 /// The current algorithm is based on Orson Peters' [pattern-defeating quicksort][pdqsort],
1321 /// which is a quicksort variant designed to be very fast on certain kinds of patterns,
1322 /// sometimes achieving linear time. It is randomized but deterministic, and falls back to
1323 /// heapsort on degenerate inputs.
1325 /// It is generally faster than stable sorting, except in a few special cases, e.g. when the
1326 /// slice consists of several concatenated sorted sequences.
1331 /// #![feature(sort_unstable)]
1333 /// let mut v = [-5i32, 4, 1, -3, 2];
1335 /// v.sort_unstable_by_key(|k| k.abs());
1336 /// assert!(v == [1, 2, -3, 4, -5]);
1339 /// [pdqsort]: https://github.com/orlp/pdqsort
1340 // FIXME #40585: Mention `sort_unstable_by_key` in the documentation for `sort_by_key`.
1341 #[unstable(feature = "sort_unstable", issue = "40585")]
1343 pub fn sort_unstable_by_key<B, F>(&mut self, f: F)
1344 where F: FnMut(&T) -> B,
1347 core_slice::SliceExt::sort_unstable_by_key(self, f);
1350 /// Permutes the slice in-place such that `self[mid..]` moves to the
1351 /// beginning of the slice while `self[..mid]` moves to the end of the
1352 /// slice. Equivalently, rotates the slice `mid` places to the left
1353 /// or `k = self.len() - mid` places to the right.
1355 /// This is a "k-rotation", a permutation in which item `i` moves to
1356 /// position `i + k`, modulo the length of the slice. See _Elements
1357 /// of Programming_ [§10.4][eop].
1359 /// Rotation by `mid` and rotation by `k` are inverse operations.
1361 /// [eop]: https://books.google.com/books?id=CO9ULZGINlsC&pg=PA178&q=k-rotation
1365 /// This function will panic if `mid` is greater than the length of the
1366 /// slice. (Note that `mid == self.len()` does _not_ panic; it's a nop
1367 /// rotation with `k == 0`, the inverse of a rotation with `mid == 0`.)
1371 /// Takes linear (in `self.len()`) time.
1376 /// #![feature(slice_rotate)]
1378 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1381 /// assert_eq!(&a, &[3, 4, 5, 6, 7, 1, 2]);
1382 /// let k = a.len() - mid;
1384 /// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7]);
1386 /// use std::ops::Range;
1387 /// fn slide<T>(slice: &mut [T], range: Range<usize>, to: usize) {
1388 /// if to < range.start {
1389 /// slice[to..range.end].rotate(range.start-to);
1390 /// } else if to > range.end {
1391 /// slice[range.start..to].rotate(range.end-range.start);
1394 /// let mut v: Vec<_> = (0..10).collect();
1395 /// slide(&mut v, 1..4, 7);
1396 /// assert_eq!(&v, &[0, 4, 5, 6, 1, 2, 3, 7, 8, 9]);
1397 /// slide(&mut v, 6..8, 1);
1398 /// assert_eq!(&v, &[0, 3, 7, 4, 5, 6, 1, 2, 8, 9]);
1400 #[unstable(feature = "slice_rotate", issue = "41891")]
1401 pub fn rotate(&mut self, mid: usize) {
1402 core_slice::SliceExt::rotate(self, mid);
1405 /// Copies the elements from `src` into `self`.
1407 /// The length of `src` must be the same as `self`.
1409 /// If `src` implements `Copy`, it can be more performant to use
1410 /// [`copy_from_slice`].
1414 /// This function will panic if the two slices have different lengths.
1419 /// let mut dst = [0, 0, 0];
1420 /// let src = [1, 2, 3];
1422 /// dst.clone_from_slice(&src);
1423 /// assert!(dst == [1, 2, 3]);
1426 /// [`copy_from_slice`]: #method.copy_from_slice
1427 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1428 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1429 core_slice::SliceExt::clone_from_slice(self, src)
1432 /// Copies all elements from `src` into `self`, using a memcpy.
1434 /// The length of `src` must be the same as `self`.
1436 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1440 /// This function will panic if the two slices have different lengths.
1445 /// let mut dst = [0, 0, 0];
1446 /// let src = [1, 2, 3];
1448 /// dst.copy_from_slice(&src);
1449 /// assert_eq!(src, dst);
1452 /// [`clone_from_slice`]: #method.clone_from_slice
1453 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1454 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1455 core_slice::SliceExt::copy_from_slice(self, src)
1458 /// Copies `self` into a new `Vec`.
1463 /// let s = [10, 40, 30];
1464 /// let x = s.to_vec();
1465 /// // Here, `s` and `x` can be modified independently.
1467 #[stable(feature = "rust1", since = "1.0.0")]
1469 pub fn to_vec(&self) -> Vec<T>
1472 // NB see hack module in this file
1476 /// Converts `self` into a vector without clones or allocation.
1478 /// The resulting vector can be converted back into a box via
1479 /// `Vec<T>`'s `into_boxed_slice` method.
1484 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1485 /// let x = s.into_vec();
1486 /// // `s` cannot be used anymore because it has been converted into `x`.
1488 /// assert_eq!(x, vec![10, 40, 30]);
1490 #[stable(feature = "rust1", since = "1.0.0")]
1492 pub fn into_vec(self: Box<Self>) -> Vec<T> {
1493 // NB see hack module in this file
1494 hack::into_vec(self)
1498 ////////////////////////////////////////////////////////////////////////////////
1499 // Extension traits for slices over specific kinds of data
1500 ////////////////////////////////////////////////////////////////////////////////
1501 #[unstable(feature = "slice_concat_ext",
1502 reason = "trait should not have to exist",
1504 /// An extension trait for concatenating slices
1505 pub trait SliceConcatExt<T: ?Sized> {
1506 #[unstable(feature = "slice_concat_ext",
1507 reason = "trait should not have to exist",
1509 /// The resulting type after concatenation
1512 /// Flattens a slice of `T` into a single value `Self::Output`.
1517 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 fn concat(&self) -> Self::Output;
1522 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1523 /// given separator between each.
1528 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1530 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1531 fn join(&self, sep: &T) -> Self::Output;
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1535 fn connect(&self, sep: &T) -> Self::Output;
1538 #[unstable(feature = "slice_concat_ext",
1539 reason = "trait should not have to exist",
1541 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
1542 type Output = Vec<T>;
1544 fn concat(&self) -> Vec<T> {
1545 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1546 let mut result = Vec::with_capacity(size);
1548 result.extend_from_slice(v.borrow())
1553 fn join(&self, sep: &T) -> Vec<T> {
1554 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1555 let mut result = Vec::with_capacity(size + self.len());
1556 let mut first = true;
1561 result.push(sep.clone())
1563 result.extend_from_slice(v.borrow())
1568 fn connect(&self, sep: &T) -> Vec<T> {
1573 ////////////////////////////////////////////////////////////////////////////////
1574 // Standard trait implementations for slices
1575 ////////////////////////////////////////////////////////////////////////////////
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<T> Borrow<[T]> for Vec<T> {
1579 fn borrow(&self) -> &[T] {
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<T> BorrowMut<[T]> for Vec<T> {
1586 fn borrow_mut(&mut self) -> &mut [T] {
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<T: Clone> ToOwned for [T] {
1593 type Owned = Vec<T>;
1595 fn to_owned(&self) -> Vec<T> {
1600 fn to_owned(&self) -> Vec<T> {
1604 fn clone_into(&self, target: &mut Vec<T>) {
1605 // drop anything in target that will not be overwritten
1606 target.truncate(self.len());
1607 let len = target.len();
1609 // reuse the contained values' allocations/resources.
1610 target.clone_from_slice(&self[..len]);
1612 // target.len <= self.len due to the truncate above, so the
1613 // slice here is always in-bounds.
1614 target.extend_from_slice(&self[len..]);
1618 ////////////////////////////////////////////////////////////////////////////////
1620 ////////////////////////////////////////////////////////////////////////////////
1622 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
1624 /// This is the integral subroutine of insertion sort.
1625 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
1626 where F: FnMut(&T, &T) -> bool
1628 if v.len() >= 2 && is_less(&v[1], &v[0]) {
1630 // There are three ways to implement insertion here:
1632 // 1. Swap adjacent elements until the first one gets to its final destination.
1633 // However, this way we copy data around more than is necessary. If elements are big
1634 // structures (costly to copy), this method will be slow.
1636 // 2. Iterate until the right place for the first element is found. Then shift the
1637 // elements succeeding it to make room for it and finally place it into the
1638 // remaining hole. This is a good method.
1640 // 3. Copy the first element into a temporary variable. Iterate until the right place
1641 // for it is found. As we go along, copy every traversed element into the slot
1642 // preceding it. Finally, copy data from the temporary variable into the remaining
1643 // hole. This method is very good. Benchmarks demonstrated slightly better
1644 // performance than with the 2nd method.
1646 // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
1647 let mut tmp = mem::ManuallyDrop::new(ptr::read(&v[0]));
1649 // Intermediate state of the insertion process is always tracked by `hole`, which
1650 // serves two purposes:
1651 // 1. Protects integrity of `v` from panics in `is_less`.
1652 // 2. Fills the remaining hole in `v` in the end.
1656 // If `is_less` panics at any point during the process, `hole` will get dropped and
1657 // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
1658 // initially held exactly once.
1659 let mut hole = InsertionHole {
1663 ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
1665 for i in 2..v.len() {
1666 if !is_less(&v[i], &*tmp) {
1669 ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1);
1670 hole.dest = &mut v[i];
1672 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
1676 // When dropped, copies from `src` into `dest`.
1677 struct InsertionHole<T> {
1682 impl<T> Drop for InsertionHole<T> {
1683 fn drop(&mut self) {
1684 unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
1689 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
1690 /// stores the result into `v[..]`.
1694 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
1695 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
1696 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
1697 where F: FnMut(&T, &T) -> bool
1700 let v = v.as_mut_ptr();
1701 let v_mid = v.offset(mid as isize);
1702 let v_end = v.offset(len as isize);
1704 // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
1705 // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
1706 // copying the lesser (or greater) one into `v`.
1708 // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
1709 // consumed first, then we must copy whatever is left of the shorter run into the remaining
1712 // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
1713 // 1. Protects integrity of `v` from panics in `is_less`.
1714 // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
1718 // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
1719 // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
1720 // object it initially held exactly once.
1723 if mid <= len - mid {
1724 // The left run is shorter.
1725 ptr::copy_nonoverlapping(v, buf, mid);
1728 end: buf.offset(mid as isize),
1732 // Initially, these pointers point to the beginnings of their arrays.
1733 let left = &mut hole.start;
1734 let mut right = v_mid;
1735 let out = &mut hole.dest;
1737 while *left < hole.end && right < v_end {
1738 // Consume the lesser side.
1739 // If equal, prefer the left run to maintain stability.
1740 let to_copy = if is_less(&*right, &**left) {
1741 get_and_increment(&mut right)
1743 get_and_increment(left)
1745 ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1);
1748 // The right run is shorter.
1749 ptr::copy_nonoverlapping(v_mid, buf, len - mid);
1752 end: buf.offset((len - mid) as isize),
1756 // Initially, these pointers point past the ends of their arrays.
1757 let left = &mut hole.dest;
1758 let right = &mut hole.end;
1759 let mut out = v_end;
1761 while v < *left && buf < *right {
1762 // Consume the greater side.
1763 // If equal, prefer the right run to maintain stability.
1764 let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) {
1765 decrement_and_get(left)
1767 decrement_and_get(right)
1769 ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1);
1772 // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
1773 // it will now be copied into the hole in `v`.
1775 unsafe fn get_and_increment<T>(ptr: &mut *mut T) -> *mut T {
1777 *ptr = ptr.offset(1);
1781 unsafe fn decrement_and_get<T>(ptr: &mut *mut T) -> *mut T {
1782 *ptr = ptr.offset(-1);
1786 // When dropped, copies the range `start..end` into `dest..`.
1787 struct MergeHole<T> {
1793 impl<T> Drop for MergeHole<T> {
1794 fn drop(&mut self) {
1795 // `T` is not a zero-sized type, so it's okay to divide by it's size.
1796 let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
1797 unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
1802 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
1803 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
1805 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1806 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1807 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1810 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1811 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1813 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
1814 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
1815 where F: FnMut(&T, &T) -> bool
1817 // Slices of up to this length get sorted using insertion sort.
1818 const MAX_INSERTION: usize = 20;
1819 // Very short runs are extended using insertion sort to span at least this many elements.
1820 const MIN_RUN: usize = 10;
1822 // Sorting has no meaningful behavior on zero-sized types.
1823 if size_of::<T>() == 0 {
1829 // Short arrays get sorted in-place via insertion sort to avoid allocations.
1830 if len <= MAX_INSERTION {
1832 for i in (0..len-1).rev() {
1833 insert_head(&mut v[i..], &mut is_less);
1839 // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1840 // shallow copies of the contents of `v` without risking the dtors running on copies if
1841 // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1842 // which will always have length at most `len / 2`.
1843 let mut buf = Vec::with_capacity(len / 2);
1845 // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
1846 // strange decision, but consider the fact that merges more often go in the opposite direction
1847 // (forwards). According to benchmarks, merging forwards is slightly faster than merging
1848 // backwards. To conclude, identifying runs by traversing backwards improves performance.
1849 let mut runs = vec![];
1852 // Find the next natural run, and reverse it if it's strictly descending.
1853 let mut start = end - 1;
1857 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
1858 while start > 0 && is_less(v.get_unchecked(start),
1859 v.get_unchecked(start - 1)) {
1862 v[start..end].reverse();
1864 while start > 0 && !is_less(v.get_unchecked(start),
1865 v.get_unchecked(start - 1)) {
1872 // Insert some more elements into the run if it's too short. Insertion sort is faster than
1873 // merge sort on short sequences, so this significantly improves performance.
1874 while start > 0 && end - start < MIN_RUN {
1876 insert_head(&mut v[start..end], &mut is_less);
1879 // Push this run onto the stack.
1886 // Merge some pairs of adjacent runs to satisfy the invariants.
1887 while let Some(r) = collapse(&runs) {
1888 let left = runs[r + 1];
1889 let right = runs[r];
1891 merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(),
1896 len: left.len + right.len,
1902 // Finally, exactly one run must remain in the stack.
1903 debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
1905 // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1906 // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1907 // algorithm should continue building a new run instead, `None` is returned.
1909 // TimSort is infamous for it's buggy implementations, as described here:
1910 // http://envisage-project.eu/timsort-specification-and-verification/
1912 // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1913 // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1914 // hold for *all* runs in the stack.
1916 // This function correctly checks invariants for the top four runs. Additionally, if the top
1917 // run starts at index 0, it will always demand a merge operation until the stack is fully
1918 // collapsed, in order to complete the sort.
1920 fn collapse(runs: &[Run]) -> Option<usize> {
1922 if n >= 2 && (runs[n - 1].start == 0 ||
1923 runs[n - 2].len <= runs[n - 1].len ||
1924 (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) ||
1925 (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) {
1926 if n >= 3 && runs[n - 3].len < runs[n - 1].len {
1936 #[derive(Clone, Copy)]