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