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