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