]> git.lizzy.rs Git - rust.git/blob - src/liballoc/slice.rs
0c5fec2cf74994379e343a3ac649725b89a257ed
[rust.git] / src / liballoc / slice.rs
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.
4 //
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.
10
11 //! A dynamically-sized view into a contiguous sequence, `[T]`.
12 //!
13 //! Slices are a view into a block of memory represented as a pointer and a
14 //! length.
15 //!
16 //! ```
17 //! // slicing a Vec
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"];
22 //! ```
23 //!
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
27 //! points to:
28 //!
29 //! ```
30 //! let x = &mut [1, 2, 3];
31 //! x[1] = 7;
32 //! assert_eq!(x, &[1, 7, 3]);
33 //! ```
34 //!
35 //! Here are some of the things this module contains:
36 //!
37 //! ## Structs
38 //!
39 //! There are several structs that are useful for slices, such as [`Iter`], which
40 //! represents iteration over a slice.
41 //!
42 //! ## Trait Implementations
43 //!
44 //! There are several implementations of common traits for slices. Some examples
45 //! include:
46 //!
47 //! * [`Clone`]
48 //! * [`Eq`], [`Ord`] - for slices whose element type are [`Eq`] or [`Ord`].
49 //! * [`Hash`] - for slices whose element type is [`Hash`].
50 //!
51 //! ## Iteration
52 //!
53 //! The slices implement `IntoIterator`. The iterator yields references to the
54 //! slice elements.
55 //!
56 //! ```
57 //! let numbers = &[0, 1, 2];
58 //! for n in numbers {
59 //!     println!("{} is a number!", n);
60 //! }
61 //! ```
62 //!
63 //! The mutable slice yields mutable references to the elements:
64 //!
65 //! ```
66 //! let mut scores = [7, 8, 9];
67 //! for score in &mut scores[..] {
68 //!     *score += 1;
69 //! }
70 //! ```
71 //!
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
74 //! `&mut i32`.
75 //!
76 //! * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
77 //!   iterators.
78 //! * Further methods that return iterators are [`.split`], [`.splitn`],
79 //!   [`.chunks`], [`.windows`] and more.
80 //!
81 //! *[See also the slice primitive type](../../std/primitive.slice.html).*
82 //!
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")]
95
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))]
99
100 use core::cmp::Ordering::{self, Less};
101 use core::mem::size_of;
102 use core::mem;
103 use core::ptr;
104 use core::slice as core_slice;
105
106 use borrow::{Borrow, BorrowMut, ToOwned};
107 use boxed::Box;
108 use vec::Vec;
109
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 = "from_ref", issue = "45703")]
123 pub use core::slice::{from_ref, from_ref_mut};
124 #[unstable(feature = "slice_get_slice", issue = "35729")]
125 pub use core::slice::SliceIndex;
126
127 ////////////////////////////////////////////////////////////////////////////////
128 // Basic slice extension methods
129 ////////////////////////////////////////////////////////////////////////////////
130
131 // HACK(japaric) needed for the implementation of `vec!` macro during testing
132 // NB see the hack module in this file for more details
133 #[cfg(test)]
134 pub use self::hack::into_vec;
135
136 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
137 // NB see the hack module in this file for more details
138 #[cfg(test)]
139 pub use self::hack::to_vec;
140
141 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
142 // functions are actually methods that are in `impl [T]` but not in
143 // `core::slice::SliceExt` - we need to supply these functions for the
144 // `test_permutations` test
145 mod hack {
146     use boxed::Box;
147     use core::mem;
148
149     #[cfg(test)]
150     use string::ToString;
151     use vec::Vec;
152
153     pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
154         unsafe {
155             let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
156             mem::forget(b);
157             xs
158         }
159     }
160
161     #[inline]
162     pub fn to_vec<T>(s: &[T]) -> Vec<T>
163         where T: Clone
164     {
165         let mut vector = Vec::with_capacity(s.len());
166         vector.extend_from_slice(s);
167         vector
168     }
169 }
170
171 #[lang = "slice"]
172 #[cfg(not(test))]
173 impl<T> [T] {
174     /// Returns the number of elements in the slice.
175     ///
176     /// # Examples
177     ///
178     /// ```
179     /// let a = [1, 2, 3];
180     /// assert_eq!(a.len(), 3);
181     /// ```
182     #[stable(feature = "rust1", since = "1.0.0")]
183     #[inline]
184     pub fn len(&self) -> usize {
185         core_slice::SliceExt::len(self)
186     }
187
188     /// Returns `true` if the slice has a length of 0.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// let a = [1, 2, 3];
194     /// assert!(!a.is_empty());
195     /// ```
196     #[stable(feature = "rust1", since = "1.0.0")]
197     #[inline]
198     pub fn is_empty(&self) -> bool {
199         core_slice::SliceExt::is_empty(self)
200     }
201
202     /// Returns the first element of the slice, or `None` if it is empty.
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// let v = [10, 40, 30];
208     /// assert_eq!(Some(&10), v.first());
209     ///
210     /// let w: &[i32] = &[];
211     /// assert_eq!(None, w.first());
212     /// ```
213     #[stable(feature = "rust1", since = "1.0.0")]
214     #[inline]
215     pub fn first(&self) -> Option<&T> {
216         core_slice::SliceExt::first(self)
217     }
218
219     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// let x = &mut [0, 1, 2];
225     ///
226     /// if let Some(first) = x.first_mut() {
227     ///     *first = 5;
228     /// }
229     /// assert_eq!(x, &[5, 1, 2]);
230     /// ```
231     #[stable(feature = "rust1", since = "1.0.0")]
232     #[inline]
233     pub fn first_mut(&mut self) -> Option<&mut T> {
234         core_slice::SliceExt::first_mut(self)
235     }
236
237     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
238     ///
239     /// # Examples
240     ///
241     /// ```
242     /// let x = &[0, 1, 2];
243     ///
244     /// if let Some((first, elements)) = x.split_first() {
245     ///     assert_eq!(first, &0);
246     ///     assert_eq!(elements, &[1, 2]);
247     /// }
248     /// ```
249     #[stable(feature = "slice_splits", since = "1.5.0")]
250     #[inline]
251     pub fn split_first(&self) -> Option<(&T, &[T])> {
252         core_slice::SliceExt::split_first(self)
253     }
254
255     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// let x = &mut [0, 1, 2];
261     ///
262     /// if let Some((first, elements)) = x.split_first_mut() {
263     ///     *first = 3;
264     ///     elements[0] = 4;
265     ///     elements[1] = 5;
266     /// }
267     /// assert_eq!(x, &[3, 4, 5]);
268     /// ```
269     #[stable(feature = "slice_splits", since = "1.5.0")]
270     #[inline]
271     pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
272         core_slice::SliceExt::split_first_mut(self)
273     }
274
275     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// let x = &[0, 1, 2];
281     ///
282     /// if let Some((last, elements)) = x.split_last() {
283     ///     assert_eq!(last, &2);
284     ///     assert_eq!(elements, &[0, 1]);
285     /// }
286     /// ```
287     #[stable(feature = "slice_splits", since = "1.5.0")]
288     #[inline]
289     pub fn split_last(&self) -> Option<(&T, &[T])> {
290         core_slice::SliceExt::split_last(self)
291
292     }
293
294     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// let x = &mut [0, 1, 2];
300     ///
301     /// if let Some((last, elements)) = x.split_last_mut() {
302     ///     *last = 3;
303     ///     elements[0] = 4;
304     ///     elements[1] = 5;
305     /// }
306     /// assert_eq!(x, &[4, 5, 3]);
307     /// ```
308     #[stable(feature = "slice_splits", since = "1.5.0")]
309     #[inline]
310     pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
311         core_slice::SliceExt::split_last_mut(self)
312     }
313
314     /// Returns the last element of the slice, or `None` if it is empty.
315     ///
316     /// # Examples
317     ///
318     /// ```
319     /// let v = [10, 40, 30];
320     /// assert_eq!(Some(&30), v.last());
321     ///
322     /// let w: &[i32] = &[];
323     /// assert_eq!(None, w.last());
324     /// ```
325     #[stable(feature = "rust1", since = "1.0.0")]
326     #[inline]
327     pub fn last(&self) -> Option<&T> {
328         core_slice::SliceExt::last(self)
329     }
330
331     /// Returns a mutable pointer to the last item in the slice.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// let x = &mut [0, 1, 2];
337     ///
338     /// if let Some(last) = x.last_mut() {
339     ///     *last = 10;
340     /// }
341     /// assert_eq!(x, &[0, 1, 10]);
342     /// ```
343     #[stable(feature = "rust1", since = "1.0.0")]
344     #[inline]
345     pub fn last_mut(&mut self) -> Option<&mut T> {
346         core_slice::SliceExt::last_mut(self)
347     }
348
349     /// Returns a reference to an element or subslice depending on the type of
350     /// index.
351     ///
352     /// - If given a position, returns a reference to the element at that
353     ///   position or `None` if out of bounds.
354     /// - If given a range, returns the subslice corresponding to that range,
355     ///   or `None` if out of bounds.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// let v = [10, 40, 30];
361     /// assert_eq!(Some(&40), v.get(1));
362     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
363     /// assert_eq!(None, v.get(3));
364     /// assert_eq!(None, v.get(0..4));
365     /// ```
366     #[stable(feature = "rust1", since = "1.0.0")]
367     #[inline]
368     pub fn get<I>(&self, index: I) -> Option<&I::Output>
369         where I: SliceIndex<Self>
370     {
371         core_slice::SliceExt::get(self, index)
372     }
373
374     /// Returns a mutable reference to an element or subslice depending on the
375     /// type of index (see [`get`]) or `None` if the index is out of bounds.
376     ///
377     /// [`get`]: #method.get
378     ///
379     /// # Examples
380     ///
381     /// ```
382     /// let x = &mut [0, 1, 2];
383     ///
384     /// if let Some(elem) = x.get_mut(1) {
385     ///     *elem = 42;
386     /// }
387     /// assert_eq!(x, &[0, 42, 2]);
388     /// ```
389     #[stable(feature = "rust1", since = "1.0.0")]
390     #[inline]
391     pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
392         where I: SliceIndex<Self>
393     {
394         core_slice::SliceExt::get_mut(self, index)
395     }
396
397     /// Returns a reference to an element or subslice, without doing bounds
398     /// checking.
399     ///
400     /// This is generally not recommended, use with caution! For a safe
401     /// alternative see [`get`].
402     ///
403     /// [`get`]: #method.get
404     ///
405     /// # Examples
406     ///
407     /// ```
408     /// let x = &[1, 2, 4];
409     ///
410     /// unsafe {
411     ///     assert_eq!(x.get_unchecked(1), &2);
412     /// }
413     /// ```
414     #[stable(feature = "rust1", since = "1.0.0")]
415     #[inline]
416     pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
417         where I: SliceIndex<Self>
418     {
419         core_slice::SliceExt::get_unchecked(self, index)
420     }
421
422     /// Returns a mutable reference to an element or subslice, without doing
423     /// bounds checking.
424     ///
425     /// This is generally not recommended, use with caution! For a safe
426     /// alternative see [`get_mut`].
427     ///
428     /// [`get_mut`]: #method.get_mut
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// let x = &mut [1, 2, 4];
434     ///
435     /// unsafe {
436     ///     let elem = x.get_unchecked_mut(1);
437     ///     *elem = 13;
438     /// }
439     /// assert_eq!(x, &[1, 13, 4]);
440     /// ```
441     #[stable(feature = "rust1", since = "1.0.0")]
442     #[inline]
443     pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
444         where I: SliceIndex<Self>
445     {
446         core_slice::SliceExt::get_unchecked_mut(self, index)
447     }
448
449     /// Returns a raw pointer to the slice's buffer.
450     ///
451     /// The caller must ensure that the slice outlives the pointer this
452     /// function returns, or else it will end up pointing to garbage.
453     ///
454     /// Modifying the container referenced by this slice may cause its buffer
455     /// to be reallocated, which would also make any pointers to it invalid.
456     ///
457     /// # Examples
458     ///
459     /// ```
460     /// let x = &[1, 2, 4];
461     /// let x_ptr = x.as_ptr();
462     ///
463     /// unsafe {
464     ///     for i in 0..x.len() {
465     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
466     ///     }
467     /// }
468     /// ```
469     #[stable(feature = "rust1", since = "1.0.0")]
470     #[inline]
471     pub fn as_ptr(&self) -> *const T {
472         core_slice::SliceExt::as_ptr(self)
473     }
474
475     /// Returns an unsafe mutable pointer to the slice's buffer.
476     ///
477     /// The caller must ensure that the slice outlives the pointer this
478     /// function returns, or else it will end up pointing to garbage.
479     ///
480     /// Modifying the container referenced by this slice may cause its buffer
481     /// to be reallocated, which would also make any pointers to it invalid.
482     ///
483     /// # Examples
484     ///
485     /// ```
486     /// let x = &mut [1, 2, 4];
487     /// let x_ptr = x.as_mut_ptr();
488     ///
489     /// unsafe {
490     ///     for i in 0..x.len() {
491     ///         *x_ptr.offset(i as isize) += 2;
492     ///     }
493     /// }
494     /// assert_eq!(x, &[3, 4, 6]);
495     /// ```
496     #[stable(feature = "rust1", since = "1.0.0")]
497     #[inline]
498     pub fn as_mut_ptr(&mut self) -> *mut T {
499         core_slice::SliceExt::as_mut_ptr(self)
500     }
501
502     /// Swaps two elements in the slice.
503     ///
504     /// # Arguments
505     ///
506     /// * a - The index of the first element
507     /// * b - The index of the second element
508     ///
509     /// # Panics
510     ///
511     /// Panics if `a` or `b` are out of bounds.
512     ///
513     /// # Examples
514     ///
515     /// ```
516     /// let mut v = ["a", "b", "c", "d"];
517     /// v.swap(1, 3);
518     /// assert!(v == ["a", "d", "c", "b"]);
519     /// ```
520     #[stable(feature = "rust1", since = "1.0.0")]
521     #[inline]
522     pub fn swap(&mut self, a: usize, b: usize) {
523         core_slice::SliceExt::swap(self, a, b)
524     }
525
526     /// Reverses the order of elements in the slice, in place.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// let mut v = [1, 2, 3];
532     /// v.reverse();
533     /// assert!(v == [3, 2, 1]);
534     /// ```
535     #[stable(feature = "rust1", since = "1.0.0")]
536     #[inline]
537     pub fn reverse(&mut self) {
538         core_slice::SliceExt::reverse(self)
539     }
540
541     /// Returns an iterator over the slice.
542     ///
543     /// # Examples
544     ///
545     /// ```
546     /// let x = &[1, 2, 4];
547     /// let mut iterator = x.iter();
548     ///
549     /// assert_eq!(iterator.next(), Some(&1));
550     /// assert_eq!(iterator.next(), Some(&2));
551     /// assert_eq!(iterator.next(), Some(&4));
552     /// assert_eq!(iterator.next(), None);
553     /// ```
554     #[stable(feature = "rust1", since = "1.0.0")]
555     #[inline]
556     pub fn iter(&self) -> Iter<T> {
557         core_slice::SliceExt::iter(self)
558     }
559
560     /// Returns an iterator that allows modifying each value.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// let x = &mut [1, 2, 4];
566     /// for elem in x.iter_mut() {
567     ///     *elem += 2;
568     /// }
569     /// assert_eq!(x, &[3, 4, 6]);
570     /// ```
571     #[stable(feature = "rust1", since = "1.0.0")]
572     #[inline]
573     pub fn iter_mut(&mut self) -> IterMut<T> {
574         core_slice::SliceExt::iter_mut(self)
575     }
576
577     /// Returns an iterator over all contiguous windows of length
578     /// `size`. The windows overlap. If the slice is shorter than
579     /// `size`, the iterator returns no values.
580     ///
581     /// # Panics
582     ///
583     /// Panics if `size` is 0.
584     ///
585     /// # Examples
586     ///
587     /// ```
588     /// let slice = ['r', 'u', 's', 't'];
589     /// let mut iter = slice.windows(2);
590     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
591     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
592     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
593     /// assert!(iter.next().is_none());
594     /// ```
595     ///
596     /// If the slice is shorter than `size`:
597     ///
598     /// ```
599     /// let slice = ['f', 'o', 'o'];
600     /// let mut iter = slice.windows(4);
601     /// assert!(iter.next().is_none());
602     /// ```
603     #[stable(feature = "rust1", since = "1.0.0")]
604     #[inline]
605     pub fn windows(&self, size: usize) -> Windows<T> {
606         core_slice::SliceExt::windows(self, size)
607     }
608
609     /// Returns an iterator over `size` elements of the slice at a
610     /// time. The chunks are slices and do not overlap. If `size` does
611     /// not divide the length of the slice, then the last chunk will
612     /// not have length `size`.
613     ///
614     /// # Panics
615     ///
616     /// Panics if `size` is 0.
617     ///
618     /// # Examples
619     ///
620     /// ```
621     /// let slice = ['l', 'o', 'r', 'e', 'm'];
622     /// let mut iter = slice.chunks(2);
623     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
624     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
625     /// assert_eq!(iter.next().unwrap(), &['m']);
626     /// assert!(iter.next().is_none());
627     /// ```
628     #[stable(feature = "rust1", since = "1.0.0")]
629     #[inline]
630     pub fn chunks(&self, size: usize) -> Chunks<T> {
631         core_slice::SliceExt::chunks(self, size)
632     }
633
634     /// Returns an iterator over `chunk_size` elements of the slice at a time.
635     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
636     /// not divide the length of the slice, then the last chunk will not
637     /// have length `chunk_size`.
638     ///
639     /// # Panics
640     ///
641     /// Panics if `chunk_size` is 0.
642     ///
643     /// # Examples
644     ///
645     /// ```
646     /// let v = &mut [0, 0, 0, 0, 0];
647     /// let mut count = 1;
648     ///
649     /// for chunk in v.chunks_mut(2) {
650     ///     for elem in chunk.iter_mut() {
651     ///         *elem += count;
652     ///     }
653     ///     count += 1;
654     /// }
655     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
656     /// ```
657     #[stable(feature = "rust1", since = "1.0.0")]
658     #[inline]
659     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
660         core_slice::SliceExt::chunks_mut(self, chunk_size)
661     }
662
663     /// Divides one slice into two at an index.
664     ///
665     /// The first will contain all indices from `[0, mid)` (excluding
666     /// the index `mid` itself) and the second will contain all
667     /// indices from `[mid, len)` (excluding the index `len` itself).
668     ///
669     /// # Panics
670     ///
671     /// Panics if `mid > len`.
672     ///
673     /// # Examples
674     ///
675     /// ```
676     /// let v = [1, 2, 3, 4, 5, 6];
677     ///
678     /// {
679     ///    let (left, right) = v.split_at(0);
680     ///    assert!(left == []);
681     ///    assert!(right == [1, 2, 3, 4, 5, 6]);
682     /// }
683     ///
684     /// {
685     ///     let (left, right) = v.split_at(2);
686     ///     assert!(left == [1, 2]);
687     ///     assert!(right == [3, 4, 5, 6]);
688     /// }
689     ///
690     /// {
691     ///     let (left, right) = v.split_at(6);
692     ///     assert!(left == [1, 2, 3, 4, 5, 6]);
693     ///     assert!(right == []);
694     /// }
695     /// ```
696     #[stable(feature = "rust1", since = "1.0.0")]
697     #[inline]
698     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
699         core_slice::SliceExt::split_at(self, mid)
700     }
701
702     /// Divides one `&mut` into two at an index.
703     ///
704     /// The first will contain all indices from `[0, mid)` (excluding
705     /// the index `mid` itself) and the second will contain all
706     /// indices from `[mid, len)` (excluding the index `len` itself).
707     ///
708     /// # Panics
709     ///
710     /// Panics if `mid > len`.
711     ///
712     /// # Examples
713     ///
714     /// ```
715     /// let mut v = [1, 0, 3, 0, 5, 6];
716     /// // scoped to restrict the lifetime of the borrows
717     /// {
718     ///     let (left, right) = v.split_at_mut(2);
719     ///     assert!(left == [1, 0]);
720     ///     assert!(right == [3, 0, 5, 6]);
721     ///     left[1] = 2;
722     ///     right[1] = 4;
723     /// }
724     /// assert!(v == [1, 2, 3, 4, 5, 6]);
725     /// ```
726     #[stable(feature = "rust1", since = "1.0.0")]
727     #[inline]
728     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
729         core_slice::SliceExt::split_at_mut(self, mid)
730     }
731
732     /// Returns an iterator over subslices separated by elements that match
733     /// `pred`. The matched element is not contained in the subslices.
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// let slice = [10, 40, 33, 20];
739     /// let mut iter = slice.split(|num| num % 3 == 0);
740     ///
741     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
742     /// assert_eq!(iter.next().unwrap(), &[20]);
743     /// assert!(iter.next().is_none());
744     /// ```
745     ///
746     /// If the first element is matched, an empty slice will be the first item
747     /// returned by the iterator. Similarly, if the last element in the slice
748     /// is matched, an empty slice will be the last item returned by the
749     /// iterator:
750     ///
751     /// ```
752     /// let slice = [10, 40, 33];
753     /// let mut iter = slice.split(|num| num % 3 == 0);
754     ///
755     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
756     /// assert_eq!(iter.next().unwrap(), &[]);
757     /// assert!(iter.next().is_none());
758     /// ```
759     ///
760     /// If two matched elements are directly adjacent, an empty slice will be
761     /// present between them:
762     ///
763     /// ```
764     /// let slice = [10, 6, 33, 20];
765     /// let mut iter = slice.split(|num| num % 3 == 0);
766     ///
767     /// assert_eq!(iter.next().unwrap(), &[10]);
768     /// assert_eq!(iter.next().unwrap(), &[]);
769     /// assert_eq!(iter.next().unwrap(), &[20]);
770     /// assert!(iter.next().is_none());
771     /// ```
772     #[stable(feature = "rust1", since = "1.0.0")]
773     #[inline]
774     pub fn split<F>(&self, pred: F) -> Split<T, F>
775         where F: FnMut(&T) -> bool
776     {
777         core_slice::SliceExt::split(self, pred)
778     }
779
780     /// Returns an iterator over mutable subslices separated by elements that
781     /// match `pred`. The matched element is not contained in the subslices.
782     ///
783     /// # Examples
784     ///
785     /// ```
786     /// let mut v = [10, 40, 30, 20, 60, 50];
787     ///
788     /// for group in v.split_mut(|num| *num % 3 == 0) {
789     ///     group[0] = 1;
790     /// }
791     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
792     /// ```
793     #[stable(feature = "rust1", since = "1.0.0")]
794     #[inline]
795     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
796         where F: FnMut(&T) -> bool
797     {
798         core_slice::SliceExt::split_mut(self, pred)
799     }
800
801     /// Returns an iterator over subslices separated by elements that match
802     /// `pred`, starting at the end of the slice and working backwards.
803     /// The matched element is not contained in the subslices.
804     ///
805     /// # Examples
806     ///
807     /// ```
808     /// #![feature(slice_rsplit)]
809     ///
810     /// let slice = [11, 22, 33, 0, 44, 55];
811     /// let mut iter = slice.rsplit(|num| *num == 0);
812     ///
813     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
814     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
815     /// assert_eq!(iter.next(), None);
816     /// ```
817     ///
818     /// As with `split()`, if the first or last element is matched, an empty
819     /// slice will be the first (or last) item returned by the iterator.
820     ///
821     /// ```
822     /// #![feature(slice_rsplit)]
823     ///
824     /// let v = &[0, 1, 1, 2, 3, 5, 8];
825     /// let mut it = v.rsplit(|n| *n % 2 == 0);
826     /// assert_eq!(it.next().unwrap(), &[]);
827     /// assert_eq!(it.next().unwrap(), &[3, 5]);
828     /// assert_eq!(it.next().unwrap(), &[1, 1]);
829     /// assert_eq!(it.next().unwrap(), &[]);
830     /// assert_eq!(it.next(), None);
831     /// ```
832     #[unstable(feature = "slice_rsplit", issue = "41020")]
833     #[inline]
834     pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
835         where F: FnMut(&T) -> bool
836     {
837         core_slice::SliceExt::rsplit(self, pred)
838     }
839
840     /// Returns an iterator over mutable subslices separated by elements that
841     /// match `pred`, starting at the end of the slice and working
842     /// backwards. The matched element is not contained in the subslices.
843     ///
844     /// # Examples
845     ///
846     /// ```
847     /// #![feature(slice_rsplit)]
848     ///
849     /// let mut v = [100, 400, 300, 200, 600, 500];
850     ///
851     /// let mut count = 0;
852     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
853     ///     count += 1;
854     ///     group[0] = count;
855     /// }
856     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
857     /// ```
858     ///
859     #[unstable(feature = "slice_rsplit", issue = "41020")]
860     #[inline]
861     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
862         where F: FnMut(&T) -> bool
863     {
864         core_slice::SliceExt::rsplit_mut(self, pred)
865     }
866
867     /// Returns an iterator over subslices separated by elements that match
868     /// `pred`, limited to returning at most `n` items. The matched element is
869     /// not contained in the subslices.
870     ///
871     /// The last element returned, if any, will contain the remainder of the
872     /// slice.
873     ///
874     /// # Examples
875     ///
876     /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
877     /// `[20, 60, 50]`):
878     ///
879     /// ```
880     /// let v = [10, 40, 30, 20, 60, 50];
881     ///
882     /// for group in v.splitn(2, |num| *num % 3 == 0) {
883     ///     println!("{:?}", group);
884     /// }
885     /// ```
886     #[stable(feature = "rust1", since = "1.0.0")]
887     #[inline]
888     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
889         where F: FnMut(&T) -> bool
890     {
891         core_slice::SliceExt::splitn(self, n, pred)
892     }
893
894     /// Returns an iterator over subslices separated by elements that match
895     /// `pred`, limited to returning at most `n` items. The matched element is
896     /// not contained in the subslices.
897     ///
898     /// The last element returned, if any, will contain the remainder of the
899     /// slice.
900     ///
901     /// # Examples
902     ///
903     /// ```
904     /// let mut v = [10, 40, 30, 20, 60, 50];
905     ///
906     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
907     ///     group[0] = 1;
908     /// }
909     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
910     /// ```
911     #[stable(feature = "rust1", since = "1.0.0")]
912     #[inline]
913     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
914         where F: FnMut(&T) -> bool
915     {
916         core_slice::SliceExt::splitn_mut(self, n, pred)
917     }
918
919     /// Returns an iterator over subslices separated by elements that match
920     /// `pred` limited to returning at most `n` items. This starts at the end of
921     /// the slice and works backwards.  The matched element is not contained in
922     /// the subslices.
923     ///
924     /// The last element returned, if any, will contain the remainder of the
925     /// slice.
926     ///
927     /// # Examples
928     ///
929     /// Print the slice split once, starting from the end, by numbers divisible
930     /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
931     ///
932     /// ```
933     /// let v = [10, 40, 30, 20, 60, 50];
934     ///
935     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
936     ///     println!("{:?}", group);
937     /// }
938     /// ```
939     #[stable(feature = "rust1", since = "1.0.0")]
940     #[inline]
941     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
942         where F: FnMut(&T) -> bool
943     {
944         core_slice::SliceExt::rsplitn(self, n, pred)
945     }
946
947     /// Returns an iterator over subslices separated by elements that match
948     /// `pred` limited to returning at most `n` items. This starts at the end of
949     /// the slice and works backwards. The matched element is not contained in
950     /// the subslices.
951     ///
952     /// The last element returned, if any, will contain the remainder of the
953     /// slice.
954     ///
955     /// # Examples
956     ///
957     /// ```
958     /// let mut s = [10, 40, 30, 20, 60, 50];
959     ///
960     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
961     ///     group[0] = 1;
962     /// }
963     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
964     /// ```
965     #[stable(feature = "rust1", since = "1.0.0")]
966     #[inline]
967     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
968         where F: FnMut(&T) -> bool
969     {
970         core_slice::SliceExt::rsplitn_mut(self, n, pred)
971     }
972
973     /// Returns `true` if the slice contains an element with the given value.
974     ///
975     /// # Examples
976     ///
977     /// ```
978     /// let v = [10, 40, 30];
979     /// assert!(v.contains(&30));
980     /// assert!(!v.contains(&50));
981     /// ```
982     #[stable(feature = "rust1", since = "1.0.0")]
983     pub fn contains(&self, x: &T) -> bool
984         where T: PartialEq
985     {
986         core_slice::SliceExt::contains(self, x)
987     }
988
989     /// Returns `true` if `needle` is a prefix of the slice.
990     ///
991     /// # Examples
992     ///
993     /// ```
994     /// let v = [10, 40, 30];
995     /// assert!(v.starts_with(&[10]));
996     /// assert!(v.starts_with(&[10, 40]));
997     /// assert!(!v.starts_with(&[50]));
998     /// assert!(!v.starts_with(&[10, 50]));
999     /// ```
1000     ///
1001     /// Always returns `true` if `needle` is an empty slice:
1002     ///
1003     /// ```
1004     /// let v = &[10, 40, 30];
1005     /// assert!(v.starts_with(&[]));
1006     /// let v: &[u8] = &[];
1007     /// assert!(v.starts_with(&[]));
1008     /// ```
1009     #[stable(feature = "rust1", since = "1.0.0")]
1010     pub fn starts_with(&self, needle: &[T]) -> bool
1011         where T: PartialEq
1012     {
1013         core_slice::SliceExt::starts_with(self, needle)
1014     }
1015
1016     /// Returns `true` if `needle` is a suffix of the slice.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```
1021     /// let v = [10, 40, 30];
1022     /// assert!(v.ends_with(&[30]));
1023     /// assert!(v.ends_with(&[40, 30]));
1024     /// assert!(!v.ends_with(&[50]));
1025     /// assert!(!v.ends_with(&[50, 30]));
1026     /// ```
1027     ///
1028     /// Always returns `true` if `needle` is an empty slice:
1029     ///
1030     /// ```
1031     /// let v = &[10, 40, 30];
1032     /// assert!(v.ends_with(&[]));
1033     /// let v: &[u8] = &[];
1034     /// assert!(v.ends_with(&[]));
1035     /// ```
1036     #[stable(feature = "rust1", since = "1.0.0")]
1037     pub fn ends_with(&self, needle: &[T]) -> bool
1038         where T: PartialEq
1039     {
1040         core_slice::SliceExt::ends_with(self, needle)
1041     }
1042
1043     /// Binary searches this sorted slice for a given element.
1044     ///
1045     /// If the value is found then `Ok` is returned, containing the
1046     /// index of the matching element; if the value is not found then
1047     /// `Err` is returned, containing the index where a matching
1048     /// element could be inserted while maintaining sorted order.
1049     ///
1050     /// # Examples
1051     ///
1052     /// Looks up a series of four elements. The first is found, with a
1053     /// uniquely determined position; the second and third are not
1054     /// found; the fourth could match any position in `[1, 4]`.
1055     ///
1056     /// ```
1057     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1058     ///
1059     /// assert_eq!(s.binary_search(&13),  Ok(9));
1060     /// assert_eq!(s.binary_search(&4),   Err(7));
1061     /// assert_eq!(s.binary_search(&100), Err(13));
1062     /// let r = s.binary_search(&1);
1063     /// assert!(match r { Ok(1...4) => true, _ => false, });
1064     /// ```
1065     #[stable(feature = "rust1", since = "1.0.0")]
1066     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1067         where T: Ord
1068     {
1069         core_slice::SliceExt::binary_search(self, x)
1070     }
1071
1072     /// Binary searches this sorted slice with a comparator function.
1073     ///
1074     /// The comparator function should implement an order consistent
1075     /// with the sort order of the underlying slice, returning an
1076     /// order code that indicates whether its argument is `Less`,
1077     /// `Equal` or `Greater` the desired target.
1078     ///
1079     /// If a matching value is found then returns `Ok`, containing
1080     /// the index for the matched element; if no match is found then
1081     /// `Err` is returned, containing the index where a matching
1082     /// element could be inserted while maintaining sorted order.
1083     ///
1084     /// # Examples
1085     ///
1086     /// Looks up a series of four elements. The first is found, with a
1087     /// uniquely determined position; the second and third are not
1088     /// found; the fourth could match any position in `[1, 4]`.
1089     ///
1090     /// ```
1091     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1092     ///
1093     /// let seek = 13;
1094     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1095     /// let seek = 4;
1096     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1097     /// let seek = 100;
1098     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1099     /// let seek = 1;
1100     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1101     /// assert!(match r { Ok(1...4) => true, _ => false, });
1102     /// ```
1103     #[stable(feature = "rust1", since = "1.0.0")]
1104     #[inline]
1105     pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1106         where F: FnMut(&'a T) -> Ordering
1107     {
1108         core_slice::SliceExt::binary_search_by(self, f)
1109     }
1110
1111     /// Binary searches this sorted slice with a key extraction function.
1112     ///
1113     /// Assumes that the slice is sorted by the key, for instance with
1114     /// [`sort_by_key`] using the same key extraction function.
1115     ///
1116     /// If a matching value is found then returns `Ok`, containing the
1117     /// index for the matched element; if no match is found then `Err`
1118     /// is returned, containing the index where a matching element could
1119     /// be inserted while maintaining sorted order.
1120     ///
1121     /// [`sort_by_key`]: #method.sort_by_key
1122     ///
1123     /// # Examples
1124     ///
1125     /// Looks up a series of four elements in a slice of pairs sorted by
1126     /// their second elements. The first is found, with a uniquely
1127     /// determined position; the second and third are not found; the
1128     /// fourth could match any position in `[1, 4]`.
1129     ///
1130     /// ```
1131     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1132     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1133     ///          (1, 21), (2, 34), (4, 55)];
1134     ///
1135     /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
1136     /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
1137     /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1138     /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1139     /// assert!(match r { Ok(1...4) => true, _ => false, });
1140     /// ```
1141     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1142     #[inline]
1143     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1144         where F: FnMut(&'a T) -> B,
1145               B: Ord
1146     {
1147         core_slice::SliceExt::binary_search_by_key(self, b, f)
1148     }
1149
1150     /// Sorts the slice.
1151     ///
1152     /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1153     ///
1154     /// When applicable, unstable sorting is preferred because it is generally faster than stable
1155     /// sorting and it doesn't allocate auxiliary memory.
1156     /// See [`sort_unstable`](#method.sort_unstable).
1157     ///
1158     /// # Current implementation
1159     ///
1160     /// The current algorithm is an adaptive, iterative merge sort inspired by
1161     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1162     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1163     /// two or more sorted sequences concatenated one after another.
1164     ///
1165     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1166     /// non-allocating insertion sort is used instead.
1167     ///
1168     /// # Examples
1169     ///
1170     /// ```
1171     /// let mut v = [-5, 4, 1, -3, 2];
1172     ///
1173     /// v.sort();
1174     /// assert!(v == [-5, -3, 1, 2, 4]);
1175     /// ```
1176     #[stable(feature = "rust1", since = "1.0.0")]
1177     #[inline]
1178     pub fn sort(&mut self)
1179         where T: Ord
1180     {
1181         merge_sort(self, |a, b| a.lt(b));
1182     }
1183
1184     /// Sorts the slice with a comparator function.
1185     ///
1186     /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1187     ///
1188     /// When applicable, unstable sorting is preferred because it is generally faster than stable
1189     /// sorting and it doesn't allocate auxiliary memory.
1190     /// See [`sort_unstable_by`](#method.sort_unstable_by).
1191     ///
1192     /// # Current implementation
1193     ///
1194     /// The current algorithm is an adaptive, iterative merge sort inspired by
1195     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1196     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1197     /// two or more sorted sequences concatenated one after another.
1198     ///
1199     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1200     /// non-allocating insertion sort is used instead.
1201     ///
1202     /// # Examples
1203     ///
1204     /// ```
1205     /// let mut v = [5, 4, 1, 3, 2];
1206     /// v.sort_by(|a, b| a.cmp(b));
1207     /// assert!(v == [1, 2, 3, 4, 5]);
1208     ///
1209     /// // reverse sorting
1210     /// v.sort_by(|a, b| b.cmp(a));
1211     /// assert!(v == [5, 4, 3, 2, 1]);
1212     /// ```
1213     #[stable(feature = "rust1", since = "1.0.0")]
1214     #[inline]
1215     pub fn sort_by<F>(&mut self, mut compare: F)
1216         where F: FnMut(&T, &T) -> Ordering
1217     {
1218         merge_sort(self, |a, b| compare(a, b) == Less);
1219     }
1220
1221     /// Sorts the slice with a key extraction function.
1222     ///
1223     /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1224     ///
1225     /// When applicable, unstable sorting is preferred because it is generally faster than stable
1226     /// sorting and it doesn't allocate auxiliary memory.
1227     /// See [`sort_unstable_by_key`](#method.sort_unstable_by_key).
1228     ///
1229     /// # Current implementation
1230     ///
1231     /// The current algorithm is an adaptive, iterative merge sort inspired by
1232     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1233     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1234     /// two or more sorted sequences concatenated one after another.
1235     ///
1236     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1237     /// non-allocating insertion sort is used instead.
1238     ///
1239     /// # Examples
1240     ///
1241     /// ```
1242     /// let mut v = [-5i32, 4, 1, -3, 2];
1243     ///
1244     /// v.sort_by_key(|k| k.abs());
1245     /// assert!(v == [1, 2, -3, 4, -5]);
1246     /// ```
1247     #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1248     #[inline]
1249     pub fn sort_by_key<B, F>(&mut self, mut f: F)
1250         where F: FnMut(&T) -> B, B: Ord
1251     {
1252         merge_sort(self, |a, b| f(a).lt(&f(b)));
1253     }
1254
1255     /// Sorts the slice, but may not preserve the order of equal elements.
1256     ///
1257     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1258     /// and `O(n log n)` worst-case.
1259     ///
1260     /// # Current implementation
1261     ///
1262     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1263     /// which combines the fast average case of randomized quicksort with the fast worst case of
1264     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1265     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1266     /// deterministic behavior.
1267     ///
1268     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1269     /// slice consists of several concatenated sorted sequences.
1270     ///
1271     /// # Examples
1272     ///
1273     /// ```
1274     /// let mut v = [-5, 4, 1, -3, 2];
1275     ///
1276     /// v.sort_unstable();
1277     /// assert!(v == [-5, -3, 1, 2, 4]);
1278     /// ```
1279     ///
1280     /// [pdqsort]: https://github.com/orlp/pdqsort
1281     #[stable(feature = "sort_unstable", since = "1.20.0")]
1282     #[inline]
1283     pub fn sort_unstable(&mut self)
1284         where T: Ord
1285     {
1286         core_slice::SliceExt::sort_unstable(self);
1287     }
1288
1289     /// Sorts the slice with a comparator function, but may not preserve the order of equal
1290     /// elements.
1291     ///
1292     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1293     /// and `O(n log n)` worst-case.
1294     ///
1295     /// # Current implementation
1296     ///
1297     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1298     /// which combines the fast average case of randomized quicksort with the fast worst case of
1299     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1300     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1301     /// deterministic behavior.
1302     ///
1303     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1304     /// slice consists of several concatenated sorted sequences.
1305     ///
1306     /// # Examples
1307     ///
1308     /// ```
1309     /// let mut v = [5, 4, 1, 3, 2];
1310     /// v.sort_unstable_by(|a, b| a.cmp(b));
1311     /// assert!(v == [1, 2, 3, 4, 5]);
1312     ///
1313     /// // reverse sorting
1314     /// v.sort_unstable_by(|a, b| b.cmp(a));
1315     /// assert!(v == [5, 4, 3, 2, 1]);
1316     /// ```
1317     ///
1318     /// [pdqsort]: https://github.com/orlp/pdqsort
1319     #[stable(feature = "sort_unstable", since = "1.20.0")]
1320     #[inline]
1321     pub fn sort_unstable_by<F>(&mut self, compare: F)
1322         where F: FnMut(&T, &T) -> Ordering
1323     {
1324         core_slice::SliceExt::sort_unstable_by(self, compare);
1325     }
1326
1327     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1328     /// elements.
1329     ///
1330     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1331     /// and `O(n log n)` worst-case.
1332     ///
1333     /// # Current implementation
1334     ///
1335     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1336     /// which combines the fast average case of randomized quicksort with the fast worst case of
1337     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1338     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1339     /// deterministic behavior.
1340     ///
1341     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1342     /// slice consists of several concatenated sorted sequences.
1343     ///
1344     /// # Examples
1345     ///
1346     /// ```
1347     /// let mut v = [-5i32, 4, 1, -3, 2];
1348     ///
1349     /// v.sort_unstable_by_key(|k| k.abs());
1350     /// assert!(v == [1, 2, -3, 4, -5]);
1351     /// ```
1352     ///
1353     /// [pdqsort]: https://github.com/orlp/pdqsort
1354     #[stable(feature = "sort_unstable", since = "1.20.0")]
1355     #[inline]
1356     pub fn sort_unstable_by_key<B, F>(&mut self, f: F)
1357         where F: FnMut(&T) -> B,
1358               B: Ord
1359     {
1360         core_slice::SliceExt::sort_unstable_by_key(self, f);
1361     }
1362
1363     /// Permutes the slice in-place such that `self[mid..]` moves to the
1364     /// beginning of the slice while `self[..mid]` moves to the end of the
1365     /// slice.  Equivalently, rotates the slice `mid` places to the left
1366     /// or `k = self.len() - mid` places to the right.
1367     ///
1368     /// This is a "k-rotation", a permutation in which item `i` moves to
1369     /// position `i + k`, modulo the length of the slice.  See _Elements
1370     /// of Programming_ [§10.4][eop].
1371     ///
1372     /// Rotation by `mid` and rotation by `k` are inverse operations.
1373     ///
1374     /// [eop]: https://books.google.com/books?id=CO9ULZGINlsC&pg=PA178&q=k-rotation
1375     ///
1376     /// # Panics
1377     ///
1378     /// This function will panic if `mid` is greater than the length of the
1379     /// slice.  (Note that `mid == self.len()` does _not_ panic; it's a nop
1380     /// rotation with `k == 0`, the inverse of a rotation with `mid == 0`.)
1381     ///
1382     /// # Complexity
1383     ///
1384     /// Takes linear (in `self.len()`) time.
1385     ///
1386     /// # Examples
1387     ///
1388     /// ```
1389     /// #![feature(slice_rotate)]
1390     ///
1391     /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1392     /// let mid = 2;
1393     /// a.rotate(mid);
1394     /// assert_eq!(&a, &[3, 4, 5, 6, 7, 1, 2]);
1395     /// let k = a.len() - mid;
1396     /// a.rotate(k);
1397     /// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7]);
1398     ///
1399     /// use std::ops::Range;
1400     /// fn slide<T>(slice: &mut [T], range: Range<usize>, to: usize) {
1401     ///     if to < range.start {
1402     ///         slice[to..range.end].rotate(range.start-to);
1403     ///     } else if to > range.end {
1404     ///         slice[range.start..to].rotate(range.end-range.start);
1405     ///     }
1406     /// }
1407     /// let mut v: Vec<_> = (0..10).collect();
1408     /// slide(&mut v, 1..4, 7);
1409     /// assert_eq!(&v, &[0, 4, 5, 6, 1, 2, 3, 7, 8, 9]);
1410     /// slide(&mut v, 6..8, 1);
1411     /// assert_eq!(&v, &[0, 3, 7, 4, 5, 6, 1, 2, 8, 9]);
1412     /// ```
1413     #[unstable(feature = "slice_rotate", issue = "41891")]
1414     pub fn rotate(&mut self, mid: usize) {
1415         core_slice::SliceExt::rotate(self, mid);
1416     }
1417
1418     /// Copies the elements from `src` into `self`.
1419     ///
1420     /// The length of `src` must be the same as `self`.
1421     ///
1422     /// If `src` implements `Copy`, it can be more performant to use
1423     /// [`copy_from_slice`].
1424     ///
1425     /// # Panics
1426     ///
1427     /// This function will panic if the two slices have different lengths.
1428     ///
1429     /// # Examples
1430     ///
1431     /// ```
1432     /// let mut dst = [0, 0, 0];
1433     /// let src = [1, 2, 3];
1434     ///
1435     /// dst.clone_from_slice(&src);
1436     /// assert!(dst == [1, 2, 3]);
1437     /// ```
1438     ///
1439     /// [`copy_from_slice`]: #method.copy_from_slice
1440     #[stable(feature = "clone_from_slice", since = "1.7.0")]
1441     pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1442         core_slice::SliceExt::clone_from_slice(self, src)
1443     }
1444
1445     /// Copies all elements from `src` into `self`, using a memcpy.
1446     ///
1447     /// The length of `src` must be the same as `self`.
1448     ///
1449     /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1450     ///
1451     /// # Panics
1452     ///
1453     /// This function will panic if the two slices have different lengths.
1454     ///
1455     /// # Examples
1456     ///
1457     /// ```
1458     /// let mut dst = [0, 0, 0];
1459     /// let src = [1, 2, 3];
1460     ///
1461     /// dst.copy_from_slice(&src);
1462     /// assert_eq!(src, dst);
1463     /// ```
1464     ///
1465     /// [`clone_from_slice`]: #method.clone_from_slice
1466     #[stable(feature = "copy_from_slice", since = "1.9.0")]
1467     pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1468         core_slice::SliceExt::copy_from_slice(self, src)
1469     }
1470
1471     /// Swaps all elements in `self` with those in `src`.
1472     ///
1473     /// The length of `src` must be the same as `self`.
1474     ///
1475     /// # Panics
1476     ///
1477     /// This function will panic if the two slices have different lengths.
1478     ///
1479     /// # Example
1480     ///
1481     /// ```
1482     /// #![feature(swap_with_slice)]
1483     ///
1484     /// let mut src = [1, 2, 3];
1485     /// let mut dst = [7, 8, 9];
1486     ///
1487     /// src.swap_with_slice(&mut dst);
1488     /// assert_eq!(src, [7, 8, 9]);
1489     /// assert_eq!(dst, [1, 2, 3]);
1490     /// ```
1491     #[unstable(feature = "swap_with_slice", issue = "44030")]
1492     pub fn swap_with_slice(&mut self, src: &mut [T]) {
1493         core_slice::SliceExt::swap_with_slice(self, src)
1494     }
1495
1496     /// Copies `self` into a new `Vec`.
1497     ///
1498     /// # Examples
1499     ///
1500     /// ```
1501     /// let s = [10, 40, 30];
1502     /// let x = s.to_vec();
1503     /// // Here, `s` and `x` can be modified independently.
1504     /// ```
1505     #[stable(feature = "rust1", since = "1.0.0")]
1506     #[inline]
1507     pub fn to_vec(&self) -> Vec<T>
1508         where T: Clone
1509     {
1510         // NB see hack module in this file
1511         hack::to_vec(self)
1512     }
1513
1514     /// Converts `self` into a vector without clones or allocation.
1515     ///
1516     /// The resulting vector can be converted back into a box via
1517     /// `Vec<T>`'s `into_boxed_slice` method.
1518     ///
1519     /// # Examples
1520     ///
1521     /// ```
1522     /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1523     /// let x = s.into_vec();
1524     /// // `s` cannot be used anymore because it has been converted into `x`.
1525     ///
1526     /// assert_eq!(x, vec![10, 40, 30]);
1527     /// ```
1528     #[stable(feature = "rust1", since = "1.0.0")]
1529     #[inline]
1530     pub fn into_vec(self: Box<Self>) -> Vec<T> {
1531         // NB see hack module in this file
1532         hack::into_vec(self)
1533     }
1534 }
1535
1536 ////////////////////////////////////////////////////////////////////////////////
1537 // Extension traits for slices over specific kinds of data
1538 ////////////////////////////////////////////////////////////////////////////////
1539 #[unstable(feature = "slice_concat_ext",
1540            reason = "trait should not have to exist",
1541            issue = "27747")]
1542 /// An extension trait for concatenating slices
1543 pub trait SliceConcatExt<T: ?Sized> {
1544     #[unstable(feature = "slice_concat_ext",
1545                reason = "trait should not have to exist",
1546                issue = "27747")]
1547     /// The resulting type after concatenation
1548     type Output;
1549
1550     /// Flattens a slice of `T` into a single value `Self::Output`.
1551     ///
1552     /// # Examples
1553     ///
1554     /// ```
1555     /// assert_eq!(["hello", "world"].concat(), "helloworld");
1556     /// assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1557     /// ```
1558     #[stable(feature = "rust1", since = "1.0.0")]
1559     fn concat(&self) -> Self::Output;
1560
1561     /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1562     /// given separator between each.
1563     ///
1564     /// # Examples
1565     ///
1566     /// ```
1567     /// assert_eq!(["hello", "world"].join(" "), "hello world");
1568     /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
1569     /// ```
1570     #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1571     fn join(&self, sep: &T) -> Self::Output;
1572
1573     #[stable(feature = "rust1", since = "1.0.0")]
1574     #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1575     fn connect(&self, sep: &T) -> Self::Output;
1576 }
1577
1578 #[unstable(feature = "slice_concat_ext",
1579            reason = "trait should not have to exist",
1580            issue = "27747")]
1581 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
1582     type Output = Vec<T>;
1583
1584     fn concat(&self) -> Vec<T> {
1585         let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1586         let mut result = Vec::with_capacity(size);
1587         for v in self {
1588             result.extend_from_slice(v.borrow())
1589         }
1590         result
1591     }
1592
1593     fn join(&self, sep: &T) -> Vec<T> {
1594         let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1595         let mut result = Vec::with_capacity(size + self.len());
1596         let mut first = true;
1597         for v in self {
1598             if first {
1599                 first = false
1600             } else {
1601                 result.push(sep.clone())
1602             }
1603             result.extend_from_slice(v.borrow())
1604         }
1605         result
1606     }
1607
1608     fn connect(&self, sep: &T) -> Vec<T> {
1609         self.join(sep)
1610     }
1611 }
1612
1613 ////////////////////////////////////////////////////////////////////////////////
1614 // Standard trait implementations for slices
1615 ////////////////////////////////////////////////////////////////////////////////
1616
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<T> Borrow<[T]> for Vec<T> {
1619     fn borrow(&self) -> &[T] {
1620         &self[..]
1621     }
1622 }
1623
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<T> BorrowMut<[T]> for Vec<T> {
1626     fn borrow_mut(&mut self) -> &mut [T] {
1627         &mut self[..]
1628     }
1629 }
1630
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: Clone> ToOwned for [T] {
1633     type Owned = Vec<T>;
1634     #[cfg(not(test))]
1635     fn to_owned(&self) -> Vec<T> {
1636         self.to_vec()
1637     }
1638
1639     #[cfg(test)]
1640     fn to_owned(&self) -> Vec<T> {
1641         hack::to_vec(self)
1642     }
1643
1644     fn clone_into(&self, target: &mut Vec<T>) {
1645         // drop anything in target that will not be overwritten
1646         target.truncate(self.len());
1647         let len = target.len();
1648
1649         // reuse the contained values' allocations/resources.
1650         target.clone_from_slice(&self[..len]);
1651
1652         // target.len <= self.len due to the truncate above, so the
1653         // slice here is always in-bounds.
1654         target.extend_from_slice(&self[len..]);
1655     }
1656 }
1657
1658 ////////////////////////////////////////////////////////////////////////////////
1659 // Sorting
1660 ////////////////////////////////////////////////////////////////////////////////
1661
1662 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
1663 ///
1664 /// This is the integral subroutine of insertion sort.
1665 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
1666     where F: FnMut(&T, &T) -> bool
1667 {
1668     if v.len() >= 2 && is_less(&v[1], &v[0]) {
1669         unsafe {
1670             // There are three ways to implement insertion here:
1671             //
1672             // 1. Swap adjacent elements until the first one gets to its final destination.
1673             //    However, this way we copy data around more than is necessary. If elements are big
1674             //    structures (costly to copy), this method will be slow.
1675             //
1676             // 2. Iterate until the right place for the first element is found. Then shift the
1677             //    elements succeeding it to make room for it and finally place it into the
1678             //    remaining hole. This is a good method.
1679             //
1680             // 3. Copy the first element into a temporary variable. Iterate until the right place
1681             //    for it is found. As we go along, copy every traversed element into the slot
1682             //    preceding it. Finally, copy data from the temporary variable into the remaining
1683             //    hole. This method is very good. Benchmarks demonstrated slightly better
1684             //    performance than with the 2nd method.
1685             //
1686             // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
1687             let mut tmp = mem::ManuallyDrop::new(ptr::read(&v[0]));
1688
1689             // Intermediate state of the insertion process is always tracked by `hole`, which
1690             // serves two purposes:
1691             // 1. Protects integrity of `v` from panics in `is_less`.
1692             // 2. Fills the remaining hole in `v` in the end.
1693             //
1694             // Panic safety:
1695             //
1696             // If `is_less` panics at any point during the process, `hole` will get dropped and
1697             // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
1698             // initially held exactly once.
1699             let mut hole = InsertionHole {
1700                 src: &mut *tmp,
1701                 dest: &mut v[1],
1702             };
1703             ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
1704
1705             for i in 2..v.len() {
1706                 if !is_less(&v[i], &*tmp) {
1707                     break;
1708                 }
1709                 ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1);
1710                 hole.dest = &mut v[i];
1711             }
1712             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
1713         }
1714     }
1715
1716     // When dropped, copies from `src` into `dest`.
1717     struct InsertionHole<T> {
1718         src: *mut T,
1719         dest: *mut T,
1720     }
1721
1722     impl<T> Drop for InsertionHole<T> {
1723         fn drop(&mut self) {
1724             unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
1725         }
1726     }
1727 }
1728
1729 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
1730 /// stores the result into `v[..]`.
1731 ///
1732 /// # Safety
1733 ///
1734 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
1735 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
1736 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
1737     where F: FnMut(&T, &T) -> bool
1738 {
1739     let len = v.len();
1740     let v = v.as_mut_ptr();
1741     let v_mid = v.offset(mid as isize);
1742     let v_end = v.offset(len as isize);
1743
1744     // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
1745     // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
1746     // copying the lesser (or greater) one into `v`.
1747     //
1748     // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
1749     // consumed first, then we must copy whatever is left of the shorter run into the remaining
1750     // hole in `v`.
1751     //
1752     // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
1753     // 1. Protects integrity of `v` from panics in `is_less`.
1754     // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
1755     //
1756     // Panic safety:
1757     //
1758     // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
1759     // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
1760     // object it initially held exactly once.
1761     let mut hole;
1762
1763     if mid <= len - mid {
1764         // The left run is shorter.
1765         ptr::copy_nonoverlapping(v, buf, mid);
1766         hole = MergeHole {
1767             start: buf,
1768             end: buf.offset(mid as isize),
1769             dest: v,
1770         };
1771
1772         // Initially, these pointers point to the beginnings of their arrays.
1773         let left = &mut hole.start;
1774         let mut right = v_mid;
1775         let out = &mut hole.dest;
1776
1777         while *left < hole.end && right < v_end {
1778             // Consume the lesser side.
1779             // If equal, prefer the left run to maintain stability.
1780             let to_copy = if is_less(&*right, &**left) {
1781                 get_and_increment(&mut right)
1782             } else {
1783                 get_and_increment(left)
1784             };
1785             ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1);
1786         }
1787     } else {
1788         // The right run is shorter.
1789         ptr::copy_nonoverlapping(v_mid, buf, len - mid);
1790         hole = MergeHole {
1791             start: buf,
1792             end: buf.offset((len - mid) as isize),
1793             dest: v_mid,
1794         };
1795
1796         // Initially, these pointers point past the ends of their arrays.
1797         let left = &mut hole.dest;
1798         let right = &mut hole.end;
1799         let mut out = v_end;
1800
1801         while v < *left && buf < *right {
1802             // Consume the greater side.
1803             // If equal, prefer the right run to maintain stability.
1804             let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) {
1805                 decrement_and_get(left)
1806             } else {
1807                 decrement_and_get(right)
1808             };
1809             ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1);
1810         }
1811     }
1812     // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
1813     // it will now be copied into the hole in `v`.
1814
1815     unsafe fn get_and_increment<T>(ptr: &mut *mut T) -> *mut T {
1816         let old = *ptr;
1817         *ptr = ptr.offset(1);
1818         old
1819     }
1820
1821     unsafe fn decrement_and_get<T>(ptr: &mut *mut T) -> *mut T {
1822         *ptr = ptr.offset(-1);
1823         *ptr
1824     }
1825
1826     // When dropped, copies the range `start..end` into `dest..`.
1827     struct MergeHole<T> {
1828         start: *mut T,
1829         end: *mut T,
1830         dest: *mut T,
1831     }
1832
1833     impl<T> Drop for MergeHole<T> {
1834         fn drop(&mut self) {
1835             // `T` is not a zero-sized type, so it's okay to divide by its size.
1836             let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
1837             unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
1838         }
1839     }
1840 }
1841
1842 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
1843 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
1844 ///
1845 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1846 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1847 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1848 /// satisfied:
1849 ///
1850 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1851 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1852 ///
1853 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
1854 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
1855     where F: FnMut(&T, &T) -> bool
1856 {
1857     // Slices of up to this length get sorted using insertion sort.
1858     const MAX_INSERTION: usize = 20;
1859     // Very short runs are extended using insertion sort to span at least this many elements.
1860     const MIN_RUN: usize = 10;
1861
1862     // Sorting has no meaningful behavior on zero-sized types.
1863     if size_of::<T>() == 0 {
1864         return;
1865     }
1866
1867     let len = v.len();
1868
1869     // Short arrays get sorted in-place via insertion sort to avoid allocations.
1870     if len <= MAX_INSERTION {
1871         if len >= 2 {
1872             for i in (0..len-1).rev() {
1873                 insert_head(&mut v[i..], &mut is_less);
1874             }
1875         }
1876         return;
1877     }
1878
1879     // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1880     // shallow copies of the contents of `v` without risking the dtors running on copies if
1881     // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1882     // which will always have length at most `len / 2`.
1883     let mut buf = Vec::with_capacity(len / 2);
1884
1885     // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
1886     // strange decision, but consider the fact that merges more often go in the opposite direction
1887     // (forwards). According to benchmarks, merging forwards is slightly faster than merging
1888     // backwards. To conclude, identifying runs by traversing backwards improves performance.
1889     let mut runs = vec![];
1890     let mut end = len;
1891     while end > 0 {
1892         // Find the next natural run, and reverse it if it's strictly descending.
1893         let mut start = end - 1;
1894         if start > 0 {
1895             start -= 1;
1896             unsafe {
1897                 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
1898                     while start > 0 && is_less(v.get_unchecked(start),
1899                                                v.get_unchecked(start - 1)) {
1900                         start -= 1;
1901                     }
1902                     v[start..end].reverse();
1903                 } else {
1904                     while start > 0 && !is_less(v.get_unchecked(start),
1905                                                 v.get_unchecked(start - 1)) {
1906                         start -= 1;
1907                     }
1908                 }
1909             }
1910         }
1911
1912         // Insert some more elements into the run if it's too short. Insertion sort is faster than
1913         // merge sort on short sequences, so this significantly improves performance.
1914         while start > 0 && end - start < MIN_RUN {
1915             start -= 1;
1916             insert_head(&mut v[start..end], &mut is_less);
1917         }
1918
1919         // Push this run onto the stack.
1920         runs.push(Run {
1921             start,
1922             len: end - start,
1923         });
1924         end = start;
1925
1926         // Merge some pairs of adjacent runs to satisfy the invariants.
1927         while let Some(r) = collapse(&runs) {
1928             let left = runs[r + 1];
1929             let right = runs[r];
1930             unsafe {
1931                 merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(),
1932                       &mut is_less);
1933             }
1934             runs[r] = Run {
1935                 start: left.start,
1936                 len: left.len + right.len,
1937             };
1938             runs.remove(r + 1);
1939         }
1940     }
1941
1942     // Finally, exactly one run must remain in the stack.
1943     debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
1944
1945     // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1946     // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1947     // algorithm should continue building a new run instead, `None` is returned.
1948     //
1949     // TimSort is infamous for its buggy implementations, as described here:
1950     // http://envisage-project.eu/timsort-specification-and-verification/
1951     //
1952     // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1953     // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1954     // hold for *all* runs in the stack.
1955     //
1956     // This function correctly checks invariants for the top four runs. Additionally, if the top
1957     // run starts at index 0, it will always demand a merge operation until the stack is fully
1958     // collapsed, in order to complete the sort.
1959     #[inline]
1960     fn collapse(runs: &[Run]) -> Option<usize> {
1961         let n = runs.len();
1962         if n >= 2 && (runs[n - 1].start == 0 ||
1963                       runs[n - 2].len <= runs[n - 1].len ||
1964                       (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) ||
1965                       (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) {
1966             if n >= 3 && runs[n - 3].len < runs[n - 1].len {
1967                 Some(n - 3)
1968             } else {
1969                 Some(n - 2)
1970             }
1971         } else {
1972             None
1973         }
1974     }
1975
1976     #[derive(Clone, Copy)]
1977     struct Run {
1978         start: usize,
1979         len: usize,
1980     }
1981 }