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