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