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