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