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