1 //! A dynamically-sized view into a contiguous sequence, `[T]`.
3 //! *[See also the slice primitive type](slice).*
5 //! Slices are a view into a block of memory represented as a pointer and a
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"];
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
22 //! let x = &mut [1, 2, 3];
24 //! assert_eq!(x, &[1, 7, 3]);
27 //! Here are some of the things this module contains:
31 //! There are several structs that are useful for slices, such as [`Iter`], which
32 //! represents iteration over a slice.
34 //! ## Trait Implementations
36 //! There are several implementations of common traits for slices. Some examples
40 //! * [`Eq`], [`Ord`] - for slices whose element type are [`Eq`] or [`Ord`].
41 //! * [`Hash`] - for slices whose element type is [`Hash`].
45 //! The slices implement `IntoIterator`. The iterator yields references to the
49 //! let numbers = &[0, 1, 2];
50 //! for n in numbers {
51 //! println!("{} is a number!", n);
55 //! The mutable slice yields mutable references to the elements:
58 //! let mut scores = [7, 8, 9];
59 //! for score in &mut scores[..] {
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
68 //! * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
70 //! * Further methods that return iterators are [`.split`], [`.splitn`],
71 //! [`.chunks`], [`.windows`] and more.
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))]
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))]
90 #[cfg(not(no_global_oom_handling))]
91 use core::mem::size_of;
92 #[cfg(not(no_global_oom_handling))]
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;
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 = "slice_get_slice", since = "1.28.0")]
112 pub use core::slice::SliceIndex;
113 #[stable(feature = "from_ref", since = "1.28.0")]
114 pub use core::slice::{from_mut, from_ref};
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub use core::slice::{Chunks, Windows};
119 #[stable(feature = "chunks_exact", since = "1.31.0")]
120 pub use core::slice::{ChunksExact, ChunksExactMut};
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub use core::slice::{ChunksMut, Split, SplitMut};
123 #[unstable(feature = "slice_group_by", issue = "80552")]
124 pub use core::slice::{GroupBy, GroupByMut};
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub use core::slice::{Iter, IterMut};
127 #[stable(feature = "rchunks", since = "1.31.0")]
128 pub use core::slice::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
129 #[stable(feature = "slice_rsplit", since = "1.27.0")]
130 pub use core::slice::{RSplit, RSplitMut};
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub use core::slice::{RSplitN, RSplitNMut, SplitN, SplitNMut};
134 ////////////////////////////////////////////////////////////////////////////////
135 // Basic slice extension methods
136 ////////////////////////////////////////////////////////////////////////////////
138 // HACK(japaric) needed for the implementation of `vec!` macro during testing
139 // N.B., see the `hack` module in this file for more details.
141 pub use hack::into_vec;
143 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
144 // N.B., see the `hack` module in this file for more details.
146 pub use hack::to_vec;
148 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
149 // functions are actually methods that are in `impl [T]` but not in
150 // `core::slice::SliceExt` - we need to supply these functions for the
151 // `test_permutations` test
153 use core::alloc::Allocator;
155 use crate::boxed::Box;
158 // We shouldn't add inline attribute to this since this is used in
159 // `vec!` macro mostly and causes perf regression. See #71204 for
160 // discussion and perf results.
161 pub fn into_vec<T, A: Allocator>(b: Box<[T], A>) -> Vec<T, A> {
164 let (b, alloc) = Box::into_raw_with_allocator(b);
165 Vec::from_raw_parts_in(b as *mut T, len, len, alloc)
169 #[cfg(not(no_global_oom_handling))]
171 pub fn to_vec<T: ConvertVec, A: Allocator>(s: &[T], alloc: A) -> Vec<T, A> {
175 #[cfg(not(no_global_oom_handling))]
176 pub trait ConvertVec {
177 fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A>
182 #[cfg(not(no_global_oom_handling))]
183 impl<T: Clone> ConvertVec for T {
185 default fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A> {
186 struct DropGuard<'a, T, A: Allocator> {
187 vec: &'a mut Vec<T, A>,
190 impl<'a, T, A: Allocator> Drop for DropGuard<'a, T, A> {
194 // items were marked initialized in the loop below
196 self.vec.set_len(self.num_init);
200 let mut vec = Vec::with_capacity_in(s.len(), alloc);
201 let mut guard = DropGuard { vec: &mut vec, num_init: 0 };
202 let slots = guard.vec.spare_capacity_mut();
203 // .take(slots.len()) is necessary for LLVM to remove bounds checks
204 // and has better codegen than zip.
205 for (i, b) in s.iter().enumerate().take(slots.len()) {
207 slots[i].write(b.clone());
209 core::mem::forget(guard);
211 // the vec was allocated and initialized above to at least this length.
213 vec.set_len(s.len());
219 #[cfg(not(no_global_oom_handling))]
220 impl<T: Copy> ConvertVec for T {
222 fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A> {
223 let mut v = Vec::with_capacity_in(s.len(), alloc);
225 // allocated above with the capacity of `s`, and initialize to `s.len()` in
226 // ptr::copy_to_non_overlapping below.
228 s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len());
236 #[lang = "slice_alloc"]
241 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
243 /// When applicable, unstable sorting is preferred because it is generally faster than stable
244 /// sorting and it doesn't allocate auxiliary memory.
245 /// See [`sort_unstable`](slice::sort_unstable).
247 /// # Current implementation
249 /// The current algorithm is an adaptive, iterative merge sort inspired by
250 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
251 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
252 /// two or more sorted sequences concatenated one after another.
254 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
255 /// non-allocating insertion sort is used instead.
260 /// let mut v = [-5, 4, 1, -3, 2];
263 /// assert!(v == [-5, -3, 1, 2, 4]);
265 #[cfg(not(no_global_oom_handling))]
266 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn sort(&mut self)
272 merge_sort(self, |a, b| a.lt(b));
275 /// Sorts the slice with a comparator function.
277 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
279 /// The comparator function must define a total ordering for the elements in the slice. If
280 /// the ordering is not total, the order of the elements is unspecified. An order is a
281 /// total order if it is (for all `a`, `b` and `c`):
283 /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
284 /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
286 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
287 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
290 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
291 /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
292 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
295 /// When applicable, unstable sorting is preferred because it is generally faster than stable
296 /// sorting and it doesn't allocate auxiliary memory.
297 /// See [`sort_unstable_by`](slice::sort_unstable_by).
299 /// # Current implementation
301 /// The current algorithm is an adaptive, iterative merge sort inspired by
302 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
303 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
304 /// two or more sorted sequences concatenated one after another.
306 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
307 /// non-allocating insertion sort is used instead.
312 /// let mut v = [5, 4, 1, 3, 2];
313 /// v.sort_by(|a, b| a.cmp(b));
314 /// assert!(v == [1, 2, 3, 4, 5]);
316 /// // reverse sorting
317 /// v.sort_by(|a, b| b.cmp(a));
318 /// assert!(v == [5, 4, 3, 2, 1]);
320 #[cfg(not(no_global_oom_handling))]
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn sort_by<F>(&mut self, mut compare: F)
325 F: FnMut(&T, &T) -> Ordering,
327 merge_sort(self, |a, b| compare(a, b) == Less);
330 /// Sorts the slice with a key extraction function.
332 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*))
333 /// worst-case, where the key function is *O*(*m*).
335 /// For expensive key functions (e.g. functions that are not simple property accesses or
336 /// basic operations), [`sort_by_cached_key`](slice::sort_by_cached_key) is likely to be
337 /// significantly faster, as it does not recompute element keys.
339 /// When applicable, unstable sorting is preferred because it is generally faster than stable
340 /// sorting and it doesn't allocate auxiliary memory.
341 /// See [`sort_unstable_by_key`](slice::sort_unstable_by_key).
343 /// # Current implementation
345 /// The current algorithm is an adaptive, iterative merge sort inspired by
346 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
347 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
348 /// two or more sorted sequences concatenated one after another.
350 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
351 /// non-allocating insertion sort is used instead.
356 /// let mut v = [-5i32, 4, 1, -3, 2];
358 /// v.sort_by_key(|k| k.abs());
359 /// assert!(v == [1, 2, -3, 4, -5]);
361 #[cfg(not(no_global_oom_handling))]
362 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
364 pub fn sort_by_key<K, F>(&mut self, mut f: F)
369 merge_sort(self, |a, b| f(a).lt(&f(b)));
372 /// Sorts the slice with a key extraction function.
374 /// During sorting, the key function is called only once per element.
376 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*))
377 /// worst-case, where the key function is *O*(*m*).
379 /// For simple key functions (e.g., functions that are property accesses or
380 /// basic operations), [`sort_by_key`](slice::sort_by_key) is likely to be
383 /// # Current implementation
385 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
386 /// which combines the fast average case of randomized quicksort with the fast worst case of
387 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
388 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
389 /// deterministic behavior.
391 /// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
392 /// length of the slice.
397 /// let mut v = [-5i32, 4, 32, -3, 2];
399 /// v.sort_by_cached_key(|k| k.to_string());
400 /// assert!(v == [-3, -5, 2, 32, 4]);
403 /// [pdqsort]: https://github.com/orlp/pdqsort
404 #[cfg(not(no_global_oom_handling))]
405 #[stable(feature = "slice_sort_by_cached_key", since = "1.34.0")]
407 pub fn sort_by_cached_key<K, F>(&mut self, f: F)
412 // Helper macro for indexing our vector by the smallest possible type, to reduce allocation.
413 macro_rules! sort_by_key {
414 ($t:ty, $slice:ident, $f:ident) => {{
415 let mut indices: Vec<_> =
416 $slice.iter().map($f).enumerate().map(|(i, k)| (k, i as $t)).collect();
417 // The elements of `indices` are unique, as they are indexed, so any sort will be
418 // stable with respect to the original slice. We use `sort_unstable` here because
419 // it requires less memory allocation.
420 indices.sort_unstable();
421 for i in 0..$slice.len() {
422 let mut index = indices[i].1;
423 while (index as usize) < i {
424 index = indices[index as usize].1;
426 indices[i].1 = index;
427 $slice.swap(i, index as usize);
432 let sz_u8 = mem::size_of::<(K, u8)>();
433 let sz_u16 = mem::size_of::<(K, u16)>();
434 let sz_u32 = mem::size_of::<(K, u32)>();
435 let sz_usize = mem::size_of::<(K, usize)>();
437 let len = self.len();
441 if sz_u8 < sz_u16 && len <= (u8::MAX as usize) {
442 return sort_by_key!(u8, self, f);
444 if sz_u16 < sz_u32 && len <= (u16::MAX as usize) {
445 return sort_by_key!(u16, self, f);
447 if sz_u32 < sz_usize && len <= (u32::MAX as usize) {
448 return sort_by_key!(u32, self, f);
450 sort_by_key!(usize, self, f)
453 /// Copies `self` into a new `Vec`.
458 /// let s = [10, 40, 30];
459 /// let x = s.to_vec();
460 /// // Here, `s` and `x` can be modified independently.
462 #[cfg(not(no_global_oom_handling))]
463 #[rustc_conversion_suggestion]
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn to_vec(&self) -> Vec<T>
470 self.to_vec_in(Global)
473 /// Copies `self` into a new `Vec` with an allocator.
478 /// #![feature(allocator_api)]
480 /// use std::alloc::System;
482 /// let s = [10, 40, 30];
483 /// let x = s.to_vec_in(System);
484 /// // Here, `s` and `x` can be modified independently.
486 #[cfg(not(no_global_oom_handling))]
488 #[unstable(feature = "allocator_api", issue = "32838")]
489 pub fn to_vec_in<A: Allocator>(&self, alloc: A) -> Vec<T, A>
493 // N.B., see the `hack` module in this file for more details.
494 hack::to_vec(self, alloc)
497 /// Converts `self` into a vector without clones or allocation.
499 /// The resulting vector can be converted back into a box via
500 /// `Vec<T>`'s `into_boxed_slice` method.
505 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
506 /// let x = s.into_vec();
507 /// // `s` cannot be used anymore because it has been converted into `x`.
509 /// assert_eq!(x, vec![10, 40, 30]);
511 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn into_vec<A: Allocator>(self: Box<Self, A>) -> Vec<T, A> {
514 // N.B., see the `hack` module in this file for more details.
518 /// Creates a vector by repeating a slice `n` times.
522 /// This function will panic if the capacity would overflow.
529 /// assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);
532 /// A panic upon overflow:
535 /// // this will panic at runtime
536 /// b"0123456789abcdef".repeat(usize::MAX);
538 #[cfg(not(no_global_oom_handling))]
539 #[stable(feature = "repeat_generic_slice", since = "1.40.0")]
540 pub fn repeat(&self, n: usize) -> Vec<T>
548 // If `n` is larger than zero, it can be split as
549 // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
550 // `2^expn` is the number represented by the leftmost '1' bit of `n`,
551 // and `rem` is the remaining part of `n`.
553 // Using `Vec` to access `set_len()`.
554 let capacity = self.len().checked_mul(n).expect("capacity overflow");
555 let mut buf = Vec::with_capacity(capacity);
557 // `2^expn` repetition is done by doubling `buf` `expn`-times.
561 // If `m > 0`, there are remaining bits up to the leftmost '1'.
563 // `buf.extend(buf)`:
565 ptr::copy_nonoverlapping(
567 (buf.as_mut_ptr() as *mut T).add(buf.len()),
570 // `buf` has capacity of `self.len() * n`.
571 let buf_len = buf.len();
572 buf.set_len(buf_len * 2);
579 // `rem` (`= n - 2^expn`) repetition is done by copying
580 // first `rem` repetitions from `buf` itself.
581 let rem_len = capacity - buf.len(); // `self.len() * rem`
583 // `buf.extend(buf[0 .. rem_len])`:
585 // This is non-overlapping since `2^expn > rem`.
586 ptr::copy_nonoverlapping(
588 (buf.as_mut_ptr() as *mut T).add(buf.len()),
591 // `buf.len() + rem_len` equals to `buf.capacity()` (`= self.len() * n`).
592 buf.set_len(capacity);
598 /// Flattens a slice of `T` into a single value `Self::Output`.
603 /// assert_eq!(["hello", "world"].concat(), "helloworld");
604 /// assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn concat<Item: ?Sized>(&self) -> <Self as Concat<Item>>::Output
614 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
615 /// given separator between each.
620 /// assert_eq!(["hello", "world"].join(" "), "hello world");
621 /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
622 /// assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
624 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
625 pub fn join<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
627 Self: Join<Separator>,
629 Join::join(self, sep)
632 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
633 /// given separator between each.
638 /// # #![allow(deprecated)]
639 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
640 /// assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
642 #[stable(feature = "rust1", since = "1.0.0")]
643 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
644 pub fn connect<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
646 Self: Join<Separator>,
648 Join::join(self, sep)
652 #[lang = "slice_u8_alloc"]
655 /// Returns a vector containing a copy of this slice where each byte
656 /// is mapped to its ASCII upper case equivalent.
658 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
659 /// but non-ASCII letters are unchanged.
661 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
663 /// [`make_ascii_uppercase`]: slice::make_ascii_uppercase
664 #[cfg(not(no_global_oom_handling))]
665 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
667 pub fn to_ascii_uppercase(&self) -> Vec<u8> {
668 let mut me = self.to_vec();
669 me.make_ascii_uppercase();
673 /// Returns a vector containing a copy of this slice where each byte
674 /// is mapped to its ASCII lower case equivalent.
676 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
677 /// but non-ASCII letters are unchanged.
679 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
681 /// [`make_ascii_lowercase`]: slice::make_ascii_lowercase
682 #[cfg(not(no_global_oom_handling))]
683 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
685 pub fn to_ascii_lowercase(&self) -> Vec<u8> {
686 let mut me = self.to_vec();
687 me.make_ascii_lowercase();
692 ////////////////////////////////////////////////////////////////////////////////
693 // Extension traits for slices over specific kinds of data
694 ////////////////////////////////////////////////////////////////////////////////
696 /// Helper trait for [`[T]::concat`](slice::concat).
698 /// Note: the `Item` type parameter is not used in this trait,
699 /// but it allows impls to be more generic.
700 /// Without it, we get this error:
703 /// error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predica
704 /// --> src/liballoc/slice.rs:608:6
706 /// 608 | impl<T: Clone, V: Borrow<[T]>> Concat for [V] {
707 /// | ^ unconstrained type parameter
710 /// This is because there could exist `V` types with multiple `Borrow<[_]>` impls,
711 /// such that multiple `T` types would apply:
714 /// # #[allow(dead_code)]
715 /// pub struct Foo(Vec<u32>, Vec<String>);
717 /// impl std::borrow::Borrow<[u32]> for Foo {
718 /// fn borrow(&self) -> &[u32] { &self.0 }
721 /// impl std::borrow::Borrow<[String]> for Foo {
722 /// fn borrow(&self) -> &[String] { &self.1 }
725 #[unstable(feature = "slice_concat_trait", issue = "27747")]
726 pub trait Concat<Item: ?Sized> {
727 #[unstable(feature = "slice_concat_trait", issue = "27747")]
728 /// The resulting type after concatenation
731 /// Implementation of [`[T]::concat`](slice::concat)
732 #[unstable(feature = "slice_concat_trait", issue = "27747")]
733 fn concat(slice: &Self) -> Self::Output;
736 /// Helper trait for [`[T]::join`](slice::join)
737 #[unstable(feature = "slice_concat_trait", issue = "27747")]
738 pub trait Join<Separator> {
739 #[unstable(feature = "slice_concat_trait", issue = "27747")]
740 /// The resulting type after concatenation
743 /// Implementation of [`[T]::join`](slice::join)
744 #[unstable(feature = "slice_concat_trait", issue = "27747")]
745 fn join(slice: &Self, sep: Separator) -> Self::Output;
748 #[cfg(not(no_global_oom_handling))]
749 #[unstable(feature = "slice_concat_ext", issue = "27747")]
750 impl<T: Clone, V: Borrow<[T]>> Concat<T> for [V] {
751 type Output = Vec<T>;
753 fn concat(slice: &Self) -> Vec<T> {
754 let size = slice.iter().map(|slice| slice.borrow().len()).sum();
755 let mut result = Vec::with_capacity(size);
757 result.extend_from_slice(v.borrow())
763 #[cfg(not(no_global_oom_handling))]
764 #[unstable(feature = "slice_concat_ext", issue = "27747")]
765 impl<T: Clone, V: Borrow<[T]>> Join<&T> for [V] {
766 type Output = Vec<T>;
768 fn join(slice: &Self, sep: &T) -> Vec<T> {
769 let mut iter = slice.iter();
770 let first = match iter.next() {
771 Some(first) => first,
772 None => return vec![],
774 let size = slice.iter().map(|v| v.borrow().len()).sum::<usize>() + slice.len() - 1;
775 let mut result = Vec::with_capacity(size);
776 result.extend_from_slice(first.borrow());
779 result.push(sep.clone());
780 result.extend_from_slice(v.borrow())
786 #[cfg(not(no_global_oom_handling))]
787 #[unstable(feature = "slice_concat_ext", issue = "27747")]
788 impl<T: Clone, V: Borrow<[T]>> Join<&[T]> for [V] {
789 type Output = Vec<T>;
791 fn join(slice: &Self, sep: &[T]) -> Vec<T> {
792 let mut iter = slice.iter();
793 let first = match iter.next() {
794 Some(first) => first,
795 None => return vec![],
798 slice.iter().map(|v| v.borrow().len()).sum::<usize>() + sep.len() * (slice.len() - 1);
799 let mut result = Vec::with_capacity(size);
800 result.extend_from_slice(first.borrow());
803 result.extend_from_slice(sep);
804 result.extend_from_slice(v.borrow())
810 ////////////////////////////////////////////////////////////////////////////////
811 // Standard trait implementations for slices
812 ////////////////////////////////////////////////////////////////////////////////
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<T> Borrow<[T]> for Vec<T> {
816 fn borrow(&self) -> &[T] {
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<T> BorrowMut<[T]> for Vec<T> {
823 fn borrow_mut(&mut self) -> &mut [T] {
828 #[cfg(not(no_global_oom_handling))]
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<T: Clone> ToOwned for [T] {
833 fn to_owned(&self) -> Vec<T> {
838 fn to_owned(&self) -> Vec<T> {
839 hack::to_vec(self, Global)
842 fn clone_into(&self, target: &mut Vec<T>) {
843 // drop anything in target that will not be overwritten
844 target.truncate(self.len());
846 // target.len <= self.len due to the truncate above, so the
847 // slices here are always in-bounds.
848 let (init, tail) = self.split_at(target.len());
850 // reuse the contained values' allocations/resources.
851 target.clone_from_slice(init);
852 target.extend_from_slice(tail);
856 ////////////////////////////////////////////////////////////////////////////////
858 ////////////////////////////////////////////////////////////////////////////////
860 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
862 /// This is the integral subroutine of insertion sort.
863 #[cfg(not(no_global_oom_handling))]
864 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
866 F: FnMut(&T, &T) -> bool,
868 if v.len() >= 2 && is_less(&v[1], &v[0]) {
870 // There are three ways to implement insertion here:
872 // 1. Swap adjacent elements until the first one gets to its final destination.
873 // However, this way we copy data around more than is necessary. If elements are big
874 // structures (costly to copy), this method will be slow.
876 // 2. Iterate until the right place for the first element is found. Then shift the
877 // elements succeeding it to make room for it and finally place it into the
878 // remaining hole. This is a good method.
880 // 3. Copy the first element into a temporary variable. Iterate until the right place
881 // for it is found. As we go along, copy every traversed element into the slot
882 // preceding it. Finally, copy data from the temporary variable into the remaining
883 // hole. This method is very good. Benchmarks demonstrated slightly better
884 // performance than with the 2nd method.
886 // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
887 let mut tmp = mem::ManuallyDrop::new(ptr::read(&v[0]));
889 // Intermediate state of the insertion process is always tracked by `hole`, which
890 // serves two purposes:
891 // 1. Protects integrity of `v` from panics in `is_less`.
892 // 2. Fills the remaining hole in `v` in the end.
896 // If `is_less` panics at any point during the process, `hole` will get dropped and
897 // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
898 // initially held exactly once.
899 let mut hole = InsertionHole { src: &mut *tmp, dest: &mut v[1] };
900 ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
902 for i in 2..v.len() {
903 if !is_less(&v[i], &*tmp) {
906 ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1);
907 hole.dest = &mut v[i];
909 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
913 // When dropped, copies from `src` into `dest`.
914 struct InsertionHole<T> {
919 impl<T> Drop for InsertionHole<T> {
922 ptr::copy_nonoverlapping(self.src, self.dest, 1);
928 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
929 /// stores the result into `v[..]`.
933 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
934 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
935 #[cfg(not(no_global_oom_handling))]
936 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
938 F: FnMut(&T, &T) -> bool,
941 let v = v.as_mut_ptr();
942 let (v_mid, v_end) = unsafe { (v.add(mid), v.add(len)) };
944 // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
945 // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
946 // copying the lesser (or greater) one into `v`.
948 // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
949 // consumed first, then we must copy whatever is left of the shorter run into the remaining
952 // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
953 // 1. Protects integrity of `v` from panics in `is_less`.
954 // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
958 // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
959 // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
960 // object it initially held exactly once.
963 if mid <= len - mid {
964 // The left run is shorter.
966 ptr::copy_nonoverlapping(v, buf, mid);
967 hole = MergeHole { start: buf, end: buf.add(mid), dest: v };
970 // Initially, these pointers point to the beginnings of their arrays.
971 let left = &mut hole.start;
972 let mut right = v_mid;
973 let out = &mut hole.dest;
975 while *left < hole.end && right < v_end {
976 // Consume the lesser side.
977 // If equal, prefer the left run to maintain stability.
979 let to_copy = if is_less(&*right, &**left) {
980 get_and_increment(&mut right)
982 get_and_increment(left)
984 ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1);
988 // The right run is shorter.
990 ptr::copy_nonoverlapping(v_mid, buf, len - mid);
991 hole = MergeHole { start: buf, end: buf.add(len - mid), dest: v_mid };
994 // Initially, these pointers point past the ends of their arrays.
995 let left = &mut hole.dest;
996 let right = &mut hole.end;
999 while v < *left && buf < *right {
1000 // Consume the greater side.
1001 // If equal, prefer the right run to maintain stability.
1003 let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) {
1004 decrement_and_get(left)
1006 decrement_and_get(right)
1008 ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1);
1012 // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
1013 // it will now be copied into the hole in `v`.
1015 unsafe fn get_and_increment<T>(ptr: &mut *mut T) -> *mut T {
1017 *ptr = unsafe { ptr.offset(1) };
1021 unsafe fn decrement_and_get<T>(ptr: &mut *mut T) -> *mut T {
1022 *ptr = unsafe { ptr.offset(-1) };
1026 // When dropped, copies the range `start..end` into `dest..`.
1027 struct MergeHole<T> {
1033 impl<T> Drop for MergeHole<T> {
1034 fn drop(&mut self) {
1035 // `T` is not a zero-sized type, so it's okay to divide by its size.
1036 let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
1038 ptr::copy_nonoverlapping(self.start, self.dest, len);
1044 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
1045 /// [here](https://github.com/python/cpython/blob/main/Objects/listsort.txt).
1047 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1048 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1049 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1052 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1053 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1055 /// The invariants ensure that the total running time is *O*(*n* \* log(*n*)) worst-case.
1056 #[cfg(not(no_global_oom_handling))]
1057 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
1059 F: FnMut(&T, &T) -> bool,
1061 // Slices of up to this length get sorted using insertion sort.
1062 const MAX_INSERTION: usize = 20;
1063 // Very short runs are extended using insertion sort to span at least this many elements.
1064 const MIN_RUN: usize = 10;
1066 // Sorting has no meaningful behavior on zero-sized types.
1067 if size_of::<T>() == 0 {
1073 // Short arrays get sorted in-place via insertion sort to avoid allocations.
1074 if len <= MAX_INSERTION {
1076 for i in (0..len - 1).rev() {
1077 insert_head(&mut v[i..], &mut is_less);
1083 // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1084 // shallow copies of the contents of `v` without risking the dtors running on copies if
1085 // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1086 // which will always have length at most `len / 2`.
1087 let mut buf = Vec::with_capacity(len / 2);
1089 // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
1090 // strange decision, but consider the fact that merges more often go in the opposite direction
1091 // (forwards). According to benchmarks, merging forwards is slightly faster than merging
1092 // backwards. To conclude, identifying runs by traversing backwards improves performance.
1093 let mut runs = vec![];
1096 // Find the next natural run, and reverse it if it's strictly descending.
1097 let mut start = end - 1;
1101 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
1102 while start > 0 && is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) {
1105 v[start..end].reverse();
1107 while start > 0 && !is_less(v.get_unchecked(start), v.get_unchecked(start - 1))
1115 // Insert some more elements into the run if it's too short. Insertion sort is faster than
1116 // merge sort on short sequences, so this significantly improves performance.
1117 while start > 0 && end - start < MIN_RUN {
1119 insert_head(&mut v[start..end], &mut is_less);
1122 // Push this run onto the stack.
1123 runs.push(Run { start, len: end - start });
1126 // Merge some pairs of adjacent runs to satisfy the invariants.
1127 while let Some(r) = collapse(&runs) {
1128 let left = runs[r + 1];
1129 let right = runs[r];
1132 &mut v[left.start..right.start + right.len],
1138 runs[r] = Run { start: left.start, len: left.len + right.len };
1143 // Finally, exactly one run must remain in the stack.
1144 debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
1146 // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1147 // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1148 // algorithm should continue building a new run instead, `None` is returned.
1150 // TimSort is infamous for its buggy implementations, as described here:
1151 // http://envisage-project.eu/timsort-specification-and-verification/
1153 // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1154 // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1155 // hold for *all* runs in the stack.
1157 // This function correctly checks invariants for the top four runs. Additionally, if the top
1158 // run starts at index 0, it will always demand a merge operation until the stack is fully
1159 // collapsed, in order to complete the sort.
1161 fn collapse(runs: &[Run]) -> Option<usize> {
1164 && (runs[n - 1].start == 0
1165 || runs[n - 2].len <= runs[n - 1].len
1166 || (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len)
1167 || (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len))
1169 if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) }
1175 #[derive(Clone, Copy)]