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