]> git.lizzy.rs Git - rust.git/blob - src/liballoc/slice.rs
liballoc: adjust abolute imports + more import fixes.
[rust.git] / src / liballoc / slice.rs
1 //! A dynamically-sized view into a contiguous sequence, `[T]`.
2 //!
3 //! *[See also the slice primitive type](../../std/primitive.slice.html).*
4 //!
5 //! Slices are a view into a block of memory represented as a pointer and a
6 //! length.
7 //!
8 //! ```
9 //! // slicing a Vec
10 //! let vec = vec![1, 2, 3];
11 //! let int_slice = &vec[..];
12 //! // coercing an array to a slice
13 //! let str_slice: &[&str] = &["one", "two", "three"];
14 //! ```
15 //!
16 //! Slices are either mutable or shared. The shared slice type is `&[T]`,
17 //! while the mutable slice type is `&mut [T]`, where `T` represents the element
18 //! type. For example, you can mutate the block of memory that a mutable slice
19 //! points to:
20 //!
21 //! ```
22 //! let x = &mut [1, 2, 3];
23 //! x[1] = 7;
24 //! assert_eq!(x, &[1, 7, 3]);
25 //! ```
26 //!
27 //! Here are some of the things this module contains:
28 //!
29 //! ## Structs
30 //!
31 //! There are several structs that are useful for slices, such as [`Iter`], which
32 //! represents iteration over a slice.
33 //!
34 //! ## Trait Implementations
35 //!
36 //! There are several implementations of common traits for slices. Some examples
37 //! include:
38 //!
39 //! * [`Clone`]
40 //! * [`Eq`], [`Ord`] - for slices whose element type are [`Eq`] or [`Ord`].
41 //! * [`Hash`] - for slices whose element type is [`Hash`].
42 //!
43 //! ## Iteration
44 //!
45 //! The slices implement `IntoIterator`. The iterator yields references to the
46 //! slice elements.
47 //!
48 //! ```
49 //! let numbers = &[0, 1, 2];
50 //! for n in numbers {
51 //!     println!("{} is a number!", n);
52 //! }
53 //! ```
54 //!
55 //! The mutable slice yields mutable references to the elements:
56 //!
57 //! ```
58 //! let mut scores = [7, 8, 9];
59 //! for score in &mut scores[..] {
60 //!     *score += 1;
61 //! }
62 //! ```
63 //!
64 //! This iterator yields mutable references to the slice's elements, so while
65 //! the element type of the slice is `i32`, the element type of the iterator is
66 //! `&mut i32`.
67 //!
68 //! * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
69 //!   iterators.
70 //! * Further methods that return iterators are [`.split`], [`.splitn`],
71 //!   [`.chunks`], [`.windows`] and more.
72 //!
73 //! [`Clone`]: ../../std/clone/trait.Clone.html
74 //! [`Eq`]: ../../std/cmp/trait.Eq.html
75 //! [`Ord`]: ../../std/cmp/trait.Ord.html
76 //! [`Iter`]: struct.Iter.html
77 //! [`Hash`]: ../../std/hash/trait.Hash.html
78 //! [`.iter`]: ../../std/primitive.slice.html#method.iter
79 //! [`.iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
80 //! [`.split`]: ../../std/primitive.slice.html#method.split
81 //! [`.splitn`]: ../../std/primitive.slice.html#method.splitn
82 //! [`.chunks`]: ../../std/primitive.slice.html#method.chunks
83 //! [`.windows`]: ../../std/primitive.slice.html#method.windows
84 #![stable(feature = "rust1", since = "1.0.0")]
85
86 // Many of the usings in this module are only used in the test configuration.
87 // It's cleaner to just turn off the unused_imports warning than to fix them.
88 #![cfg_attr(test, allow(unused_imports, dead_code))]
89
90 use core::{
91     cmp::Ordering::{self, Less},
92     mem::{self, size_of},
93     ptr,
94     u8, u16, u32,
95 };
96
97 use crate::{
98     borrow::{Borrow, BorrowMut, ToOwned},
99     boxed::Box,
100     vec::Vec,
101 };
102
103 #[stable(feature = "rust1", since = "1.0.0")]
104 pub use core::slice::{Chunks, Windows};
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub use core::slice::{Iter, IterMut};
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub use core::slice::{SplitMut, ChunksMut, Split};
109 #[stable(feature = "rust1", since = "1.0.0")]
110 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
111 #[stable(feature = "slice_rsplit", since = "1.27.0")]
112 pub use core::slice::{RSplit, RSplitMut};
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
115 #[stable(feature = "from_ref", since = "1.28.0")]
116 pub use core::slice::{from_ref, from_mut};
117 #[stable(feature = "slice_get_slice", since = "1.28.0")]
118 pub use core::slice::SliceIndex;
119 #[stable(feature = "chunks_exact", since = "1.31.0")]
120 pub use core::slice::{ChunksExact, ChunksExactMut};
121 #[stable(feature = "rchunks", since = "1.31.0")]
122 pub use core::slice::{RChunks, RChunksMut, RChunksExact, RChunksExactMut};
123
124 ////////////////////////////////////////////////////////////////////////////////
125 // Basic slice extension methods
126 ////////////////////////////////////////////////////////////////////////////////
127
128 // HACK(japaric) needed for the implementation of `vec!` macro during testing
129 // NB see the hack module in this file for more details
130 #[cfg(test)]
131 pub use self::hack::into_vec;
132
133 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
134 // NB see the hack module in this file for more details
135 #[cfg(test)]
136 pub use self::hack::to_vec;
137
138 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
139 // functions are actually methods that are in `impl [T]` but not in
140 // `core::slice::SliceExt` - we need to supply these functions for the
141 // `test_permutations` test
142 mod hack {
143     use core::mem;
144     use crate::{boxed::Box, vec::Vec};
145
146     #[cfg(test)]
147     use crate::string::ToString;
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_alloc"]
168 #[cfg(not(test))]
169 impl<T> [T] {
170     /// Sorts the slice.
171     ///
172     /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case.
173     ///
174     /// When applicable, unstable sorting is preferred because it is generally faster than stable
175     /// sorting and it doesn't allocate auxiliary memory.
176     /// See [`sort_unstable`](#method.sort_unstable).
177     ///
178     /// # Current implementation
179     ///
180     /// The current algorithm is an adaptive, iterative merge sort inspired by
181     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
182     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
183     /// two or more sorted sequences concatenated one after another.
184     ///
185     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
186     /// non-allocating insertion sort is used instead.
187     ///
188     /// # Examples
189     ///
190     /// ```
191     /// let mut v = [-5, 4, 1, -3, 2];
192     ///
193     /// v.sort();
194     /// assert!(v == [-5, -3, 1, 2, 4]);
195     /// ```
196     #[stable(feature = "rust1", since = "1.0.0")]
197     #[inline]
198     pub fn sort(&mut self)
199         where T: Ord
200     {
201         merge_sort(self, |a, b| a.lt(b));
202     }
203
204     /// Sorts the slice with a comparator function.
205     ///
206     /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case.
207     ///
208     /// The comparator function must define a total ordering for the elements in the slice. If
209     /// the ordering is not total, the order of the elements is unspecified. An order is a
210     /// total order if it is (for all a, b and c):
211     ///
212     /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
213     /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
214     ///
215     /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
216     /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
217     ///
218     /// ```
219     /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
220     /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
221     /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
222     /// ```
223     ///
224     /// When applicable, unstable sorting is preferred because it is generally faster than stable
225     /// sorting and it doesn't allocate auxiliary memory.
226     /// See [`sort_unstable_by`](#method.sort_unstable_by).
227     ///
228     /// # Current implementation
229     ///
230     /// The current algorithm is an adaptive, iterative merge sort inspired by
231     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
232     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
233     /// two or more sorted sequences concatenated one after another.
234     ///
235     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
236     /// non-allocating insertion sort is used instead.
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// let mut v = [5, 4, 1, 3, 2];
242     /// v.sort_by(|a, b| a.cmp(b));
243     /// assert!(v == [1, 2, 3, 4, 5]);
244     ///
245     /// // reverse sorting
246     /// v.sort_by(|a, b| b.cmp(a));
247     /// assert!(v == [5, 4, 3, 2, 1]);
248     /// ```
249     #[stable(feature = "rust1", since = "1.0.0")]
250     #[inline]
251     pub fn sort_by<F>(&mut self, mut compare: F)
252         where F: FnMut(&T, &T) -> Ordering
253     {
254         merge_sort(self, |a, b| compare(a, b) == Less);
255     }
256
257     /// Sorts the slice with a key extraction function.
258     ///
259     /// This sort is stable (i.e., does not reorder equal elements) and `O(m n log(m n))`
260     /// worst-case, where the key function is `O(m)`.
261     ///
262     /// When applicable, unstable sorting is preferred because it is generally faster than stable
263     /// sorting and it doesn't allocate auxiliary memory.
264     /// See [`sort_unstable_by_key`](#method.sort_unstable_by_key).
265     ///
266     /// # Current implementation
267     ///
268     /// The current algorithm is an adaptive, iterative merge sort inspired by
269     /// [timsort](https://en.wikipedia.org/wiki/Timsort).
270     /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
271     /// two or more sorted sequences concatenated one after another.
272     ///
273     /// Also, it allocates temporary storage half the size of `self`, but for short slices a
274     /// non-allocating insertion sort is used instead.
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// let mut v = [-5i32, 4, 1, -3, 2];
280     ///
281     /// v.sort_by_key(|k| k.abs());
282     /// assert!(v == [1, 2, -3, 4, -5]);
283     /// ```
284     #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
285     #[inline]
286     pub fn sort_by_key<K, F>(&mut self, mut f: F)
287         where F: FnMut(&T) -> K, K: Ord
288     {
289         merge_sort(self, |a, b| f(a).lt(&f(b)));
290     }
291
292     /// Sorts the slice with a key extraction function.
293     ///
294     /// During sorting, the key function is called only once per element.
295     ///
296     /// This sort is stable (i.e., does not reorder equal elements) and `O(m n + n log n)`
297     /// worst-case, where the key function is `O(m)`.
298     ///
299     /// For simple key functions (e.g., functions that are property accesses or
300     /// basic operations), [`sort_by_key`](#method.sort_by_key) is likely to be
301     /// faster.
302     ///
303     /// # Current implementation
304     ///
305     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
306     /// which combines the fast average case of randomized quicksort with the fast worst case of
307     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
308     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
309     /// deterministic behavior.
310     ///
311     /// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
312     /// length of the slice.
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// #![feature(slice_sort_by_cached_key)]
318     /// let mut v = [-5i32, 4, 32, -3, 2];
319     ///
320     /// v.sort_by_cached_key(|k| k.to_string());
321     /// assert!(v == [-3, -5, 2, 32, 4]);
322     /// ```
323     ///
324     /// [pdqsort]: https://github.com/orlp/pdqsort
325     #[unstable(feature = "slice_sort_by_cached_key", issue = "34447")]
326     #[inline]
327     pub fn sort_by_cached_key<K, F>(&mut self, f: F)
328         where F: FnMut(&T) -> K, K: Ord
329     {
330         // Helper macro for indexing our vector by the smallest possible type, to reduce allocation.
331         macro_rules! sort_by_key {
332             ($t:ty, $slice:ident, $f:ident) => ({
333                 let mut indices: Vec<_> =
334                     $slice.iter().map($f).enumerate().map(|(i, k)| (k, i as $t)).collect();
335                 // The elements of `indices` are unique, as they are indexed, so any sort will be
336                 // stable with respect to the original slice. We use `sort_unstable` here because
337                 // it requires less memory allocation.
338                 indices.sort_unstable();
339                 for i in 0..$slice.len() {
340                     let mut index = indices[i].1;
341                     while (index as usize) < i {
342                         index = indices[index as usize].1;
343                     }
344                     indices[i].1 = index;
345                     $slice.swap(i, index as usize);
346                 }
347             })
348         }
349
350         let sz_u8    = mem::size_of::<(K, u8)>();
351         let sz_u16   = mem::size_of::<(K, u16)>();
352         let sz_u32   = mem::size_of::<(K, u32)>();
353         let sz_usize = mem::size_of::<(K, usize)>();
354
355         let len = self.len();
356         if len < 2 { return }
357         if sz_u8  < sz_u16   && len <= ( u8::MAX as usize) { return sort_by_key!( u8, self, f) }
358         if sz_u16 < sz_u32   && len <= (u16::MAX as usize) { return sort_by_key!(u16, self, f) }
359         if sz_u32 < sz_usize && len <= (u32::MAX as usize) { return sort_by_key!(u32, self, f) }
360         sort_by_key!(usize, self, f)
361     }
362
363     /// Copies `self` into a new `Vec`.
364     ///
365     /// # Examples
366     ///
367     /// ```
368     /// let s = [10, 40, 30];
369     /// let x = s.to_vec();
370     /// // Here, `s` and `x` can be modified independently.
371     /// ```
372     #[rustc_conversion_suggestion]
373     #[stable(feature = "rust1", since = "1.0.0")]
374     #[inline]
375     pub fn to_vec(&self) -> Vec<T>
376         where T: Clone
377     {
378         // NB see hack module in this file
379         hack::to_vec(self)
380     }
381
382     /// Converts `self` into a vector without clones or allocation.
383     ///
384     /// The resulting vector can be converted back into a box via
385     /// `Vec<T>`'s `into_boxed_slice` method.
386     ///
387     /// # Examples
388     ///
389     /// ```
390     /// let s: Box<[i32]> = Box::new([10, 40, 30]);
391     /// let x = s.into_vec();
392     /// // `s` cannot be used anymore because it has been converted into `x`.
393     ///
394     /// assert_eq!(x, vec![10, 40, 30]);
395     /// ```
396     #[stable(feature = "rust1", since = "1.0.0")]
397     #[inline]
398     pub fn into_vec(self: Box<Self>) -> Vec<T> {
399         // NB see hack module in this file
400         hack::into_vec(self)
401     }
402
403     /// Creates a vector by repeating a slice `n` times.
404     ///
405     /// # Panics
406     ///
407     /// This function will panic if the capacity would overflow.
408     ///
409     /// # Examples
410     ///
411     /// Basic usage:
412     ///
413     /// ```
414     /// #![feature(repeat_generic_slice)]
415     ///
416     /// fn main() {
417     ///     assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);
418     /// }
419     /// ```
420     ///
421     /// A panic upon overflow:
422     ///
423     /// ```should_panic
424     /// #![feature(repeat_generic_slice)]
425     /// fn main() {
426     ///     // this will panic at runtime
427     ///     b"0123456789abcdef".repeat(usize::max_value());
428     /// }
429     /// ```
430     #[unstable(feature = "repeat_generic_slice",
431                reason = "it's on str, why not on slice?",
432                issue = "48784")]
433     pub fn repeat(&self, n: usize) -> Vec<T> where T: Copy {
434         if n == 0 {
435             return Vec::new();
436         }
437
438         // If `n` is larger than zero, it can be split as
439         // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
440         // `2^expn` is the number represented by the leftmost '1' bit of `n`,
441         // and `rem` is the remaining part of `n`.
442
443         // Using `Vec` to access `set_len()`.
444         let mut buf = Vec::with_capacity(self.len().checked_mul(n).expect("capacity overflow"));
445
446         // `2^expn` repetition is done by doubling `buf` `expn`-times.
447         buf.extend(self);
448         {
449             let mut m = n >> 1;
450             // If `m > 0`, there are remaining bits up to the leftmost '1'.
451             while m > 0 {
452                 // `buf.extend(buf)`:
453                 unsafe {
454                     ptr::copy_nonoverlapping(
455                         buf.as_ptr(),
456                         (buf.as_mut_ptr() as *mut T).add(buf.len()),
457                         buf.len(),
458                     );
459                     // `buf` has capacity of `self.len() * n`.
460                     let buf_len = buf.len();
461                     buf.set_len(buf_len * 2);
462                 }
463
464                 m >>= 1;
465             }
466         }
467
468         // `rem` (`= n - 2^expn`) repetition is done by copying
469         // first `rem` repetitions from `buf` itself.
470         let rem_len = self.len() * n - buf.len(); // `self.len() * rem`
471         if rem_len > 0 {
472             // `buf.extend(buf[0 .. rem_len])`:
473             unsafe {
474                 // This is non-overlapping since `2^expn > rem`.
475                 ptr::copy_nonoverlapping(
476                     buf.as_ptr(),
477                     (buf.as_mut_ptr() as *mut T).add(buf.len()),
478                     rem_len,
479                 );
480                 // `buf.len() + rem_len` equals to `buf.capacity()` (`= self.len() * n`).
481                 let buf_cap = buf.capacity();
482                 buf.set_len(buf_cap);
483             }
484         }
485         buf
486     }
487 }
488
489 #[lang = "slice_u8_alloc"]
490 #[cfg(not(test))]
491 impl [u8] {
492     /// Returns a vector containing a copy of this slice where each byte
493     /// is mapped to its ASCII upper case equivalent.
494     ///
495     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
496     /// but non-ASCII letters are unchanged.
497     ///
498     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
499     ///
500     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
501     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
502     #[inline]
503     pub fn to_ascii_uppercase(&self) -> Vec<u8> {
504         let mut me = self.to_vec();
505         me.make_ascii_uppercase();
506         me
507     }
508
509     /// Returns a vector containing a copy of this slice where each byte
510     /// is mapped to its ASCII lower case equivalent.
511     ///
512     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
513     /// but non-ASCII letters are unchanged.
514     ///
515     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
516     ///
517     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
518     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
519     #[inline]
520     pub fn to_ascii_lowercase(&self) -> Vec<u8> {
521         let mut me = self.to_vec();
522         me.make_ascii_lowercase();
523         me
524     }
525 }
526
527 ////////////////////////////////////////////////////////////////////////////////
528 // Extension traits for slices over specific kinds of data
529 ////////////////////////////////////////////////////////////////////////////////
530 #[unstable(feature = "slice_concat_ext",
531            reason = "trait should not have to exist",
532            issue = "27747")]
533 /// An extension trait for concatenating slices
534 ///
535 /// While this trait is unstable, the methods are stable. `SliceConcatExt` is
536 /// included in the [standard library prelude], so you can use [`join()`] and
537 /// [`concat()`] as if they existed on `[T]` itself.
538 ///
539 /// [standard library prelude]: ../../std/prelude/index.html
540 /// [`join()`]: #tymethod.join
541 /// [`concat()`]: #tymethod.concat
542 pub trait SliceConcatExt<T: ?Sized> {
543     #[unstable(feature = "slice_concat_ext",
544                reason = "trait should not have to exist",
545                issue = "27747")]
546     /// The resulting type after concatenation
547     type Output;
548
549     /// Flattens a slice of `T` into a single value `Self::Output`.
550     ///
551     /// # Examples
552     ///
553     /// ```
554     /// assert_eq!(["hello", "world"].concat(), "helloworld");
555     /// assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
556     /// ```
557     #[stable(feature = "rust1", since = "1.0.0")]
558     fn concat(&self) -> Self::Output;
559
560     /// Flattens a slice of `T` into a single value `Self::Output`, placing a
561     /// given separator between each.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// assert_eq!(["hello", "world"].join(" "), "hello world");
567     /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
568     /// ```
569     #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
570     fn join(&self, sep: &T) -> Self::Output;
571
572     #[stable(feature = "rust1", since = "1.0.0")]
573     #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
574     fn connect(&self, sep: &T) -> Self::Output;
575 }
576
577 #[unstable(feature = "slice_concat_ext",
578            reason = "trait should not have to exist",
579            issue = "27747")]
580 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
581     type Output = Vec<T>;
582
583     fn concat(&self) -> Vec<T> {
584         let size = self.iter().map(|slice| slice.borrow().len()).sum();
585         let mut result = Vec::with_capacity(size);
586         for v in self {
587             result.extend_from_slice(v.borrow())
588         }
589         result
590     }
591
592     fn join(&self, sep: &T) -> Vec<T> {
593         let mut iter = self.iter();
594         let first = match iter.next() {
595             Some(first) => first,
596             None => return vec![],
597         };
598         let size = self.iter().map(|slice| slice.borrow().len()).sum::<usize>() + self.len() - 1;
599         let mut result = Vec::with_capacity(size);
600         result.extend_from_slice(first.borrow());
601
602         for v in iter {
603             result.push(sep.clone());
604             result.extend_from_slice(v.borrow())
605         }
606         result
607     }
608
609     fn connect(&self, sep: &T) -> Vec<T> {
610         self.join(sep)
611     }
612 }
613
614 ////////////////////////////////////////////////////////////////////////////////
615 // Standard trait implementations for slices
616 ////////////////////////////////////////////////////////////////////////////////
617
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl<T> Borrow<[T]> for Vec<T> {
620     fn borrow(&self) -> &[T] {
621         &self[..]
622     }
623 }
624
625 #[stable(feature = "rust1", since = "1.0.0")]
626 impl<T> BorrowMut<[T]> for Vec<T> {
627     fn borrow_mut(&mut self) -> &mut [T] {
628         &mut self[..]
629     }
630 }
631
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<T: Clone> ToOwned for [T] {
634     type Owned = Vec<T>;
635     #[cfg(not(test))]
636     fn to_owned(&self) -> Vec<T> {
637         self.to_vec()
638     }
639
640     #[cfg(test)]
641     fn to_owned(&self) -> Vec<T> {
642         hack::to_vec(self)
643     }
644
645     fn clone_into(&self, target: &mut Vec<T>) {
646         // drop anything in target that will not be overwritten
647         target.truncate(self.len());
648         let len = target.len();
649
650         // reuse the contained values' allocations/resources.
651         target.clone_from_slice(&self[..len]);
652
653         // target.len <= self.len due to the truncate above, so the
654         // slice here is always in-bounds.
655         target.extend_from_slice(&self[len..]);
656     }
657 }
658
659 ////////////////////////////////////////////////////////////////////////////////
660 // Sorting
661 ////////////////////////////////////////////////////////////////////////////////
662
663 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
664 ///
665 /// This is the integral subroutine of insertion sort.
666 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
667     where F: FnMut(&T, &T) -> bool
668 {
669     if v.len() >= 2 && is_less(&v[1], &v[0]) {
670         unsafe {
671             // There are three ways to implement insertion here:
672             //
673             // 1. Swap adjacent elements until the first one gets to its final destination.
674             //    However, this way we copy data around more than is necessary. If elements are big
675             //    structures (costly to copy), this method will be slow.
676             //
677             // 2. Iterate until the right place for the first element is found. Then shift the
678             //    elements succeeding it to make room for it and finally place it into the
679             //    remaining hole. This is a good method.
680             //
681             // 3. Copy the first element into a temporary variable. Iterate until the right place
682             //    for it is found. As we go along, copy every traversed element into the slot
683             //    preceding it. Finally, copy data from the temporary variable into the remaining
684             //    hole. This method is very good. Benchmarks demonstrated slightly better
685             //    performance than with the 2nd method.
686             //
687             // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
688             let mut tmp = mem::ManuallyDrop::new(ptr::read(&v[0]));
689
690             // Intermediate state of the insertion process is always tracked by `hole`, which
691             // serves two purposes:
692             // 1. Protects integrity of `v` from panics in `is_less`.
693             // 2. Fills the remaining hole in `v` in the end.
694             //
695             // Panic safety:
696             //
697             // If `is_less` panics at any point during the process, `hole` will get dropped and
698             // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
699             // initially held exactly once.
700             let mut hole = InsertionHole {
701                 src: &mut *tmp,
702                 dest: &mut v[1],
703             };
704             ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
705
706             for i in 2..v.len() {
707                 if !is_less(&v[i], &*tmp) {
708                     break;
709                 }
710                 ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1);
711                 hole.dest = &mut v[i];
712             }
713             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
714         }
715     }
716
717     // When dropped, copies from `src` into `dest`.
718     struct InsertionHole<T> {
719         src: *mut T,
720         dest: *mut T,
721     }
722
723     impl<T> Drop for InsertionHole<T> {
724         fn drop(&mut self) {
725             unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
726         }
727     }
728 }
729
730 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
731 /// stores the result into `v[..]`.
732 ///
733 /// # Safety
734 ///
735 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
736 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
737 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
738     where F: FnMut(&T, &T) -> bool
739 {
740     let len = v.len();
741     let v = v.as_mut_ptr();
742     let v_mid = v.add(mid);
743     let v_end = v.add(len);
744
745     // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
746     // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
747     // copying the lesser (or greater) one into `v`.
748     //
749     // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
750     // consumed first, then we must copy whatever is left of the shorter run into the remaining
751     // hole in `v`.
752     //
753     // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
754     // 1. Protects integrity of `v` from panics in `is_less`.
755     // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
756     //
757     // Panic safety:
758     //
759     // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
760     // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
761     // object it initially held exactly once.
762     let mut hole;
763
764     if mid <= len - mid {
765         // The left run is shorter.
766         ptr::copy_nonoverlapping(v, buf, mid);
767         hole = MergeHole {
768             start: buf,
769             end: buf.add(mid),
770             dest: v,
771         };
772
773         // Initially, these pointers point to the beginnings of their arrays.
774         let left = &mut hole.start;
775         let mut right = v_mid;
776         let out = &mut hole.dest;
777
778         while *left < hole.end && right < v_end {
779             // Consume the lesser side.
780             // If equal, prefer the left run to maintain stability.
781             let to_copy = if is_less(&*right, &**left) {
782                 get_and_increment(&mut right)
783             } else {
784                 get_and_increment(left)
785             };
786             ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1);
787         }
788     } else {
789         // The right run is shorter.
790         ptr::copy_nonoverlapping(v_mid, buf, len - mid);
791         hole = MergeHole {
792             start: buf,
793             end: buf.add(len - mid),
794             dest: v_mid,
795         };
796
797         // Initially, these pointers point past the ends of their arrays.
798         let left = &mut hole.dest;
799         let right = &mut hole.end;
800         let mut out = v_end;
801
802         while v < *left && buf < *right {
803             // Consume the greater side.
804             // If equal, prefer the right run to maintain stability.
805             let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) {
806                 decrement_and_get(left)
807             } else {
808                 decrement_and_get(right)
809             };
810             ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1);
811         }
812     }
813     // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
814     // it will now be copied into the hole in `v`.
815
816     unsafe fn get_and_increment<T>(ptr: &mut *mut T) -> *mut T {
817         let old = *ptr;
818         *ptr = ptr.offset(1);
819         old
820     }
821
822     unsafe fn decrement_and_get<T>(ptr: &mut *mut T) -> *mut T {
823         *ptr = ptr.offset(-1);
824         *ptr
825     }
826
827     // When dropped, copies the range `start..end` into `dest..`.
828     struct MergeHole<T> {
829         start: *mut T,
830         end: *mut T,
831         dest: *mut T,
832     }
833
834     impl<T> Drop for MergeHole<T> {
835         fn drop(&mut self) {
836             // `T` is not a zero-sized type, so it's okay to divide by its size.
837             let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
838             unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
839         }
840     }
841 }
842
843 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
844 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
845 ///
846 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
847 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
848 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
849 /// satisfied:
850 ///
851 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
852 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
853 ///
854 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
855 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
856     where F: FnMut(&T, &T) -> bool
857 {
858     // Slices of up to this length get sorted using insertion sort.
859     const MAX_INSERTION: usize = 20;
860     // Very short runs are extended using insertion sort to span at least this many elements.
861     const MIN_RUN: usize = 10;
862
863     // Sorting has no meaningful behavior on zero-sized types.
864     if size_of::<T>() == 0 {
865         return;
866     }
867
868     let len = v.len();
869
870     // Short arrays get sorted in-place via insertion sort to avoid allocations.
871     if len <= MAX_INSERTION {
872         if len >= 2 {
873             for i in (0..len-1).rev() {
874                 insert_head(&mut v[i..], &mut is_less);
875             }
876         }
877         return;
878     }
879
880     // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
881     // shallow copies of the contents of `v` without risking the dtors running on copies if
882     // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
883     // which will always have length at most `len / 2`.
884     let mut buf = Vec::with_capacity(len / 2);
885
886     // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
887     // strange decision, but consider the fact that merges more often go in the opposite direction
888     // (forwards). According to benchmarks, merging forwards is slightly faster than merging
889     // backwards. To conclude, identifying runs by traversing backwards improves performance.
890     let mut runs = vec![];
891     let mut end = len;
892     while end > 0 {
893         // Find the next natural run, and reverse it if it's strictly descending.
894         let mut start = end - 1;
895         if start > 0 {
896             start -= 1;
897             unsafe {
898                 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
899                     while start > 0 && is_less(v.get_unchecked(start),
900                                                v.get_unchecked(start - 1)) {
901                         start -= 1;
902                     }
903                     v[start..end].reverse();
904                 } else {
905                     while start > 0 && !is_less(v.get_unchecked(start),
906                                                 v.get_unchecked(start - 1)) {
907                         start -= 1;
908                     }
909                 }
910             }
911         }
912
913         // Insert some more elements into the run if it's too short. Insertion sort is faster than
914         // merge sort on short sequences, so this significantly improves performance.
915         while start > 0 && end - start < MIN_RUN {
916             start -= 1;
917             insert_head(&mut v[start..end], &mut is_less);
918         }
919
920         // Push this run onto the stack.
921         runs.push(Run {
922             start,
923             len: end - start,
924         });
925         end = start;
926
927         // Merge some pairs of adjacent runs to satisfy the invariants.
928         while let Some(r) = collapse(&runs) {
929             let left = runs[r + 1];
930             let right = runs[r];
931             unsafe {
932                 merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(),
933                       &mut is_less);
934             }
935             runs[r] = Run {
936                 start: left.start,
937                 len: left.len + right.len,
938             };
939             runs.remove(r + 1);
940         }
941     }
942
943     // Finally, exactly one run must remain in the stack.
944     debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
945
946     // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
947     // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
948     // algorithm should continue building a new run instead, `None` is returned.
949     //
950     // TimSort is infamous for its buggy implementations, as described here:
951     // http://envisage-project.eu/timsort-specification-and-verification/
952     //
953     // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
954     // Enforcing them on just top three is not sufficient to ensure that the invariants will still
955     // hold for *all* runs in the stack.
956     //
957     // This function correctly checks invariants for the top four runs. Additionally, if the top
958     // run starts at index 0, it will always demand a merge operation until the stack is fully
959     // collapsed, in order to complete the sort.
960     #[inline]
961     fn collapse(runs: &[Run]) -> Option<usize> {
962         let n = runs.len();
963         if n >= 2 && (runs[n - 1].start == 0 ||
964                       runs[n - 2].len <= runs[n - 1].len ||
965                       (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) ||
966                       (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) {
967             if n >= 3 && runs[n - 3].len < runs[n - 1].len {
968                 Some(n - 3)
969             } else {
970                 Some(n - 2)
971             }
972         } else {
973             None
974         }
975     }
976
977     #[derive(Clone, Copy)]
978     struct Run {
979         start: usize,
980         len: usize,
981     }
982 }