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