1 //! Utilities for the slice primitive type.
3 //! *[See also the slice primitive type](slice).*
5 //! Most of the structs in this module are iterator types which can only be created
6 //! using a certain function. For example, `slice.iter()` yields an [`Iter`].
8 //! A few functions are provided to create a slice from a value reference
9 //! or from a raw pointer.
10 #![stable(feature = "rust1", since = "1.0.0")]
11 // Many of the usings in this module are only used in the test configuration.
12 // It's cleaner to just turn off the unused_imports warning than to fix them.
13 #![cfg_attr(test, allow(unused_imports, dead_code))]
15 use core::borrow::{Borrow, BorrowMut};
16 #[cfg(not(no_global_oom_handling))]
17 use core::cmp::Ordering::{self, Less};
18 #[cfg(not(no_global_oom_handling))]
19 use core::mem::{self, SizedTypeProperties};
20 #[cfg(not(no_global_oom_handling))]
22 #[cfg(not(no_global_oom_handling))]
23 use core::slice::sort;
25 use crate::alloc::Allocator;
26 #[cfg(not(no_global_oom_handling))]
27 use crate::alloc::{self, Global};
28 #[cfg(not(no_global_oom_handling))]
29 use crate::borrow::ToOwned;
30 use crate::boxed::Box;
36 #[unstable(feature = "slice_range", issue = "76393")]
37 pub use core::slice::range;
38 #[unstable(feature = "array_chunks", issue = "74985")]
39 pub use core::slice::ArrayChunks;
40 #[unstable(feature = "array_chunks", issue = "74985")]
41 pub use core::slice::ArrayChunksMut;
42 #[unstable(feature = "array_windows", issue = "75027")]
43 pub use core::slice::ArrayWindows;
44 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
45 pub use core::slice::EscapeAscii;
46 #[stable(feature = "slice_get_slice", since = "1.28.0")]
47 pub use core::slice::SliceIndex;
48 #[stable(feature = "from_ref", since = "1.28.0")]
49 pub use core::slice::{from_mut, from_ref};
50 #[unstable(feature = "slice_from_ptr_range", issue = "89792")]
51 pub use core::slice::{from_mut_ptr_range, from_ptr_range};
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub use core::slice::{Chunks, Windows};
56 #[stable(feature = "chunks_exact", since = "1.31.0")]
57 pub use core::slice::{ChunksExact, ChunksExactMut};
58 #[stable(feature = "rust1", since = "1.0.0")]
59 pub use core::slice::{ChunksMut, Split, SplitMut};
60 #[unstable(feature = "slice_group_by", issue = "80552")]
61 pub use core::slice::{GroupBy, GroupByMut};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::slice::{Iter, IterMut};
64 #[stable(feature = "rchunks", since = "1.31.0")]
65 pub use core::slice::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
66 #[stable(feature = "slice_rsplit", since = "1.27.0")]
67 pub use core::slice::{RSplit, RSplitMut};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::slice::{RSplitN, RSplitNMut, SplitN, SplitNMut};
70 #[stable(feature = "split_inclusive", since = "1.51.0")]
71 pub use core::slice::{SplitInclusive, SplitInclusiveMut};
73 ////////////////////////////////////////////////////////////////////////////////
74 // Basic slice extension methods
75 ////////////////////////////////////////////////////////////////////////////////
77 // HACK(japaric) needed for the implementation of `vec!` macro during testing
78 // N.B., see the `hack` module in this file for more details.
80 pub use hack::into_vec;
82 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
83 // N.B., see the `hack` module in this file for more details.
87 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
88 // functions are actually methods that are in `impl [T]` but not in
89 // `core::slice::SliceExt` - we need to supply these functions for the
90 // `test_permutations` test
92 use core::alloc::Allocator;
94 use crate::boxed::Box;
97 // We shouldn't add inline attribute to this since this is used in
98 // `vec!` macro mostly and causes perf regression. See #71204 for
99 // discussion and perf results.
100 pub fn into_vec<T, A: Allocator>(b: Box<[T], A>) -> Vec<T, A> {
103 let (b, alloc) = Box::into_raw_with_allocator(b);
104 Vec::from_raw_parts_in(b as *mut T, len, len, alloc)
108 #[cfg(not(no_global_oom_handling))]
110 pub fn to_vec<T: ConvertVec, A: Allocator>(s: &[T], alloc: A) -> Vec<T, A> {
114 #[cfg(not(no_global_oom_handling))]
115 pub trait ConvertVec {
116 fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A>
121 #[cfg(not(no_global_oom_handling))]
122 impl<T: Clone> ConvertVec for T {
124 default fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A> {
125 struct DropGuard<'a, T, A: Allocator> {
126 vec: &'a mut Vec<T, A>,
129 impl<'a, T, A: Allocator> Drop for DropGuard<'a, T, A> {
133 // items were marked initialized in the loop below
135 self.vec.set_len(self.num_init);
139 let mut vec = Vec::with_capacity_in(s.len(), alloc);
140 let mut guard = DropGuard { vec: &mut vec, num_init: 0 };
141 let slots = guard.vec.spare_capacity_mut();
142 // .take(slots.len()) is necessary for LLVM to remove bounds checks
143 // and has better codegen than zip.
144 for (i, b) in s.iter().enumerate().take(slots.len()) {
146 slots[i].write(b.clone());
148 core::mem::forget(guard);
150 // the vec was allocated and initialized above to at least this length.
152 vec.set_len(s.len());
158 #[cfg(not(no_global_oom_handling))]
159 impl<T: Copy> ConvertVec for T {
161 fn to_vec<A: Allocator>(s: &[Self], alloc: A) -> Vec<Self, A> {
162 let mut v = Vec::with_capacity_in(s.len(), alloc);
164 // allocated above with the capacity of `s`, and initialize to `s.len()` in
165 // ptr::copy_to_non_overlapping below.
167 s.as_ptr().copy_to_nonoverlapping(v.as_mut_ptr(), s.len());
179 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
181 /// When applicable, unstable sorting is preferred because it is generally faster than stable
182 /// sorting and it doesn't allocate auxiliary memory.
183 /// See [`sort_unstable`](slice::sort_unstable).
185 /// # Current implementation
187 /// The current algorithm is an adaptive, iterative merge sort inspired by
188 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
189 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
190 /// two or more sorted sequences concatenated one after another.
192 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
193 /// non-allocating insertion sort is used instead.
198 /// let mut v = [-5, 4, 1, -3, 2];
201 /// assert!(v == [-5, -3, 1, 2, 4]);
203 #[cfg(not(no_global_oom_handling))]
204 #[rustc_allow_incoherent_impl]
205 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn sort(&mut self)
211 stable_sort(self, T::lt);
214 /// Sorts the slice with a comparator function.
216 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.
218 /// The comparator function must define a total ordering for the elements in the slice. If
219 /// the ordering is not total, the order of the elements is unspecified. An order is a
220 /// total order if it is (for all `a`, `b` and `c`):
222 /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
223 /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
225 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
226 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
229 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
230 /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
231 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
234 /// When applicable, unstable sorting is preferred because it is generally faster than stable
235 /// sorting and it doesn't allocate auxiliary memory.
236 /// See [`sort_unstable_by`](slice::sort_unstable_by).
238 /// # Current implementation
240 /// The current algorithm is an adaptive, iterative merge sort inspired by
241 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
242 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
243 /// two or more sorted sequences concatenated one after another.
245 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
246 /// non-allocating insertion sort is used instead.
251 /// let mut v = [5, 4, 1, 3, 2];
252 /// v.sort_by(|a, b| a.cmp(b));
253 /// assert!(v == [1, 2, 3, 4, 5]);
255 /// // reverse sorting
256 /// v.sort_by(|a, b| b.cmp(a));
257 /// assert!(v == [5, 4, 3, 2, 1]);
259 #[cfg(not(no_global_oom_handling))]
260 #[rustc_allow_incoherent_impl]
261 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn sort_by<F>(&mut self, mut compare: F)
265 F: FnMut(&T, &T) -> Ordering,
267 stable_sort(self, |a, b| compare(a, b) == Less);
270 /// Sorts the slice with a key extraction function.
272 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*))
273 /// worst-case, where the key function is *O*(*m*).
275 /// For expensive key functions (e.g. functions that are not simple property accesses or
276 /// basic operations), [`sort_by_cached_key`](slice::sort_by_cached_key) is likely to be
277 /// significantly faster, as it does not recompute element keys.
279 /// When applicable, unstable sorting is preferred because it is generally faster than stable
280 /// sorting and it doesn't allocate auxiliary memory.
281 /// See [`sort_unstable_by_key`](slice::sort_unstable_by_key).
283 /// # Current implementation
285 /// The current algorithm is an adaptive, iterative merge sort inspired by
286 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
287 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
288 /// two or more sorted sequences concatenated one after another.
290 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
291 /// non-allocating insertion sort is used instead.
296 /// let mut v = [-5i32, 4, 1, -3, 2];
298 /// v.sort_by_key(|k| k.abs());
299 /// assert!(v == [1, 2, -3, 4, -5]);
301 #[cfg(not(no_global_oom_handling))]
302 #[rustc_allow_incoherent_impl]
303 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
305 pub fn sort_by_key<K, F>(&mut self, mut f: F)
310 stable_sort(self, |a, b| f(a).lt(&f(b)));
313 /// Sorts the slice with a key extraction function.
315 /// During sorting, the key function is called at most once per element, by using
316 /// temporary storage to remember the results of key evaluation.
317 /// The order of calls to the key function is unspecified and may change in future versions
318 /// of the standard library.
320 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*))
321 /// worst-case, where the key function is *O*(*m*).
323 /// For simple key functions (e.g., functions that are property accesses or
324 /// basic operations), [`sort_by_key`](slice::sort_by_key) is likely to be
327 /// # Current implementation
329 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
330 /// which combines the fast average case of randomized quicksort with the fast worst case of
331 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
332 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
333 /// deterministic behavior.
335 /// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
336 /// length of the slice.
341 /// let mut v = [-5i32, 4, 32, -3, 2];
343 /// v.sort_by_cached_key(|k| k.to_string());
344 /// assert!(v == [-3, -5, 2, 32, 4]);
347 /// [pdqsort]: https://github.com/orlp/pdqsort
348 #[cfg(not(no_global_oom_handling))]
349 #[rustc_allow_incoherent_impl]
350 #[stable(feature = "slice_sort_by_cached_key", since = "1.34.0")]
352 pub fn sort_by_cached_key<K, F>(&mut self, f: F)
357 // Helper macro for indexing our vector by the smallest possible type, to reduce allocation.
358 macro_rules! sort_by_key {
359 ($t:ty, $slice:ident, $f:ident) => {{
360 let mut indices: Vec<_> =
361 $slice.iter().map($f).enumerate().map(|(i, k)| (k, i as $t)).collect();
362 // The elements of `indices` are unique, as they are indexed, so any sort will be
363 // stable with respect to the original slice. We use `sort_unstable` here because
364 // it requires less memory allocation.
365 indices.sort_unstable();
366 for i in 0..$slice.len() {
367 let mut index = indices[i].1;
368 while (index as usize) < i {
369 index = indices[index as usize].1;
371 indices[i].1 = index;
372 $slice.swap(i, index as usize);
377 let sz_u8 = mem::size_of::<(K, u8)>();
378 let sz_u16 = mem::size_of::<(K, u16)>();
379 let sz_u32 = mem::size_of::<(K, u32)>();
380 let sz_usize = mem::size_of::<(K, usize)>();
382 let len = self.len();
386 if sz_u8 < sz_u16 && len <= (u8::MAX as usize) {
387 return sort_by_key!(u8, self, f);
389 if sz_u16 < sz_u32 && len <= (u16::MAX as usize) {
390 return sort_by_key!(u16, self, f);
392 if sz_u32 < sz_usize && len <= (u32::MAX as usize) {
393 return sort_by_key!(u32, self, f);
395 sort_by_key!(usize, self, f)
398 /// Copies `self` into a new `Vec`.
403 /// let s = [10, 40, 30];
404 /// let x = s.to_vec();
405 /// // Here, `s` and `x` can be modified independently.
407 #[cfg(not(no_global_oom_handling))]
408 #[rustc_allow_incoherent_impl]
409 #[rustc_conversion_suggestion]
410 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn to_vec(&self) -> Vec<T>
416 self.to_vec_in(Global)
419 /// Copies `self` into a new `Vec` with an allocator.
424 /// #![feature(allocator_api)]
426 /// use std::alloc::System;
428 /// let s = [10, 40, 30];
429 /// let x = s.to_vec_in(System);
430 /// // Here, `s` and `x` can be modified independently.
432 #[cfg(not(no_global_oom_handling))]
433 #[rustc_allow_incoherent_impl]
435 #[unstable(feature = "allocator_api", issue = "32838")]
436 pub fn to_vec_in<A: Allocator>(&self, alloc: A) -> Vec<T, A>
440 // N.B., see the `hack` module in this file for more details.
441 hack::to_vec(self, alloc)
444 /// Converts `self` into a vector without clones or allocation.
446 /// The resulting vector can be converted back into a box via
447 /// `Vec<T>`'s `into_boxed_slice` method.
452 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
453 /// let x = s.into_vec();
454 /// // `s` cannot be used anymore because it has been converted into `x`.
456 /// assert_eq!(x, vec![10, 40, 30]);
458 #[rustc_allow_incoherent_impl]
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn into_vec<A: Allocator>(self: Box<Self, A>) -> Vec<T, A> {
462 // N.B., see the `hack` module in this file for more details.
466 /// Creates a vector by copying a slice `n` times.
470 /// This function will panic if the capacity would overflow.
477 /// assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);
480 /// A panic upon overflow:
483 /// // this will panic at runtime
484 /// b"0123456789abcdef".repeat(usize::MAX);
486 #[rustc_allow_incoherent_impl]
487 #[cfg(not(no_global_oom_handling))]
488 #[stable(feature = "repeat_generic_slice", since = "1.40.0")]
489 pub fn repeat(&self, n: usize) -> Vec<T>
497 // If `n` is larger than zero, it can be split as
498 // `n = 2^expn + rem (2^expn > rem, expn >= 0, rem >= 0)`.
499 // `2^expn` is the number represented by the leftmost '1' bit of `n`,
500 // and `rem` is the remaining part of `n`.
502 // Using `Vec` to access `set_len()`.
503 let capacity = self.len().checked_mul(n).expect("capacity overflow");
504 let mut buf = Vec::with_capacity(capacity);
506 // `2^expn` repetition is done by doubling `buf` `expn`-times.
510 // If `m > 0`, there are remaining bits up to the leftmost '1'.
512 // `buf.extend(buf)`:
514 ptr::copy_nonoverlapping(
516 (buf.as_mut_ptr() as *mut T).add(buf.len()),
519 // `buf` has capacity of `self.len() * n`.
520 let buf_len = buf.len();
521 buf.set_len(buf_len * 2);
528 // `rem` (`= n - 2^expn`) repetition is done by copying
529 // first `rem` repetitions from `buf` itself.
530 let rem_len = capacity - buf.len(); // `self.len() * rem`
532 // `buf.extend(buf[0 .. rem_len])`:
534 // This is non-overlapping since `2^expn > rem`.
535 ptr::copy_nonoverlapping(
537 (buf.as_mut_ptr() as *mut T).add(buf.len()),
540 // `buf.len() + rem_len` equals to `buf.capacity()` (`= self.len() * n`).
541 buf.set_len(capacity);
547 /// Flattens a slice of `T` into a single value `Self::Output`.
552 /// assert_eq!(["hello", "world"].concat(), "helloworld");
553 /// assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
555 #[rustc_allow_incoherent_impl]
556 #[stable(feature = "rust1", since = "1.0.0")]
557 pub fn concat<Item: ?Sized>(&self) -> <Self as Concat<Item>>::Output
564 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
565 /// given separator between each.
570 /// assert_eq!(["hello", "world"].join(" "), "hello world");
571 /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
572 /// assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
574 #[rustc_allow_incoherent_impl]
575 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
576 pub fn join<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
578 Self: Join<Separator>,
580 Join::join(self, sep)
583 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
584 /// given separator between each.
589 /// # #![allow(deprecated)]
590 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
591 /// assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
593 #[rustc_allow_incoherent_impl]
594 #[stable(feature = "rust1", since = "1.0.0")]
595 #[deprecated(since = "1.3.0", note = "renamed to join")]
596 pub fn connect<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
598 Self: Join<Separator>,
600 Join::join(self, sep)
606 /// Returns a vector containing a copy of this slice where each byte
607 /// is mapped to its ASCII upper case equivalent.
609 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
610 /// but non-ASCII letters are unchanged.
612 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
614 /// [`make_ascii_uppercase`]: slice::make_ascii_uppercase
615 #[cfg(not(no_global_oom_handling))]
616 #[rustc_allow_incoherent_impl]
617 #[must_use = "this returns the uppercase bytes as a new Vec, \
618 without modifying the original"]
619 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
621 pub fn to_ascii_uppercase(&self) -> Vec<u8> {
622 let mut me = self.to_vec();
623 me.make_ascii_uppercase();
627 /// Returns a vector containing a copy of this slice where each byte
628 /// is mapped to its ASCII lower case equivalent.
630 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
631 /// but non-ASCII letters are unchanged.
633 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
635 /// [`make_ascii_lowercase`]: slice::make_ascii_lowercase
636 #[cfg(not(no_global_oom_handling))]
637 #[rustc_allow_incoherent_impl]
638 #[must_use = "this returns the lowercase bytes as a new Vec, \
639 without modifying the original"]
640 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
642 pub fn to_ascii_lowercase(&self) -> Vec<u8> {
643 let mut me = self.to_vec();
644 me.make_ascii_lowercase();
649 ////////////////////////////////////////////////////////////////////////////////
650 // Extension traits for slices over specific kinds of data
651 ////////////////////////////////////////////////////////////////////////////////
653 /// Helper trait for [`[T]::concat`](slice::concat).
655 /// Note: the `Item` type parameter is not used in this trait,
656 /// but it allows impls to be more generic.
657 /// Without it, we get this error:
660 /// error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predica
661 /// --> library/alloc/src/slice.rs:608:6
663 /// 608 | impl<T: Clone, V: Borrow<[T]>> Concat for [V] {
664 /// | ^ unconstrained type parameter
667 /// This is because there could exist `V` types with multiple `Borrow<[_]>` impls,
668 /// such that multiple `T` types would apply:
671 /// # #[allow(dead_code)]
672 /// pub struct Foo(Vec<u32>, Vec<String>);
674 /// impl std::borrow::Borrow<[u32]> for Foo {
675 /// fn borrow(&self) -> &[u32] { &self.0 }
678 /// impl std::borrow::Borrow<[String]> for Foo {
679 /// fn borrow(&self) -> &[String] { &self.1 }
682 #[unstable(feature = "slice_concat_trait", issue = "27747")]
683 pub trait Concat<Item: ?Sized> {
684 #[unstable(feature = "slice_concat_trait", issue = "27747")]
685 /// The resulting type after concatenation
688 /// Implementation of [`[T]::concat`](slice::concat)
689 #[unstable(feature = "slice_concat_trait", issue = "27747")]
690 fn concat(slice: &Self) -> Self::Output;
693 /// Helper trait for [`[T]::join`](slice::join)
694 #[unstable(feature = "slice_concat_trait", issue = "27747")]
695 pub trait Join<Separator> {
696 #[unstable(feature = "slice_concat_trait", issue = "27747")]
697 /// The resulting type after concatenation
700 /// Implementation of [`[T]::join`](slice::join)
701 #[unstable(feature = "slice_concat_trait", issue = "27747")]
702 fn join(slice: &Self, sep: Separator) -> Self::Output;
705 #[cfg(not(no_global_oom_handling))]
706 #[unstable(feature = "slice_concat_ext", issue = "27747")]
707 impl<T: Clone, V: Borrow<[T]>> Concat<T> for [V] {
708 type Output = Vec<T>;
710 fn concat(slice: &Self) -> Vec<T> {
711 let size = slice.iter().map(|slice| slice.borrow().len()).sum();
712 let mut result = Vec::with_capacity(size);
714 result.extend_from_slice(v.borrow())
720 #[cfg(not(no_global_oom_handling))]
721 #[unstable(feature = "slice_concat_ext", issue = "27747")]
722 impl<T: Clone, V: Borrow<[T]>> Join<&T> for [V] {
723 type Output = Vec<T>;
725 fn join(slice: &Self, sep: &T) -> Vec<T> {
726 let mut iter = slice.iter();
727 let first = match iter.next() {
728 Some(first) => first,
729 None => return vec![],
731 let size = slice.iter().map(|v| v.borrow().len()).sum::<usize>() + slice.len() - 1;
732 let mut result = Vec::with_capacity(size);
733 result.extend_from_slice(first.borrow());
736 result.push(sep.clone());
737 result.extend_from_slice(v.borrow())
743 #[cfg(not(no_global_oom_handling))]
744 #[unstable(feature = "slice_concat_ext", issue = "27747")]
745 impl<T: Clone, V: Borrow<[T]>> Join<&[T]> for [V] {
746 type Output = Vec<T>;
748 fn join(slice: &Self, sep: &[T]) -> Vec<T> {
749 let mut iter = slice.iter();
750 let first = match iter.next() {
751 Some(first) => first,
752 None => return vec![],
755 slice.iter().map(|v| v.borrow().len()).sum::<usize>() + sep.len() * (slice.len() - 1);
756 let mut result = Vec::with_capacity(size);
757 result.extend_from_slice(first.borrow());
760 result.extend_from_slice(sep);
761 result.extend_from_slice(v.borrow())
767 ////////////////////////////////////////////////////////////////////////////////
768 // Standard trait implementations for slices
769 ////////////////////////////////////////////////////////////////////////////////
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<T, A: Allocator> Borrow<[T]> for Vec<T, A> {
773 fn borrow(&self) -> &[T] {
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<T, A: Allocator> BorrowMut<[T]> for Vec<T, A> {
780 fn borrow_mut(&mut self) -> &mut [T] {
785 #[cfg(not(no_global_oom_handling))]
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<T: Clone> ToOwned for [T] {
790 fn to_owned(&self) -> Vec<T> {
795 fn to_owned(&self) -> Vec<T> {
796 hack::to_vec(self, Global)
799 fn clone_into(&self, target: &mut Vec<T>) {
800 // drop anything in target that will not be overwritten
801 target.truncate(self.len());
803 // target.len <= self.len due to the truncate above, so the
804 // slices here are always in-bounds.
805 let (init, tail) = self.split_at(target.len());
807 // reuse the contained values' allocations/resources.
808 target.clone_from_slice(init);
809 target.extend_from_slice(tail);
813 ////////////////////////////////////////////////////////////////////////////////
815 ////////////////////////////////////////////////////////////////////////////////
818 #[cfg(not(no_global_oom_handling))]
819 fn stable_sort<T, F>(v: &mut [T], mut is_less: F)
821 F: FnMut(&T, &T) -> bool,
824 // Sorting has no meaningful behavior on zero-sized types. Do nothing.
828 let elem_alloc_fn = |len: usize| -> *mut T {
829 // SAFETY: Creating the layout is safe as long as merge_sort never calls this with len >
830 // v.len(). Alloc in general will only be used as 'shadow-region' to store temporary swap
832 unsafe { alloc::alloc(alloc::Layout::array::<T>(len).unwrap_unchecked()) as *mut T }
835 let elem_dealloc_fn = |buf_ptr: *mut T, len: usize| {
836 // SAFETY: Creating the layout is safe as long as merge_sort never calls this with len >
837 // v.len(). The caller must ensure that buf_ptr was created by elem_alloc_fn with the same
840 alloc::dealloc(buf_ptr as *mut u8, alloc::Layout::array::<T>(len).unwrap_unchecked());
844 let run_alloc_fn = |len: usize| -> *mut sort::TimSortRun {
845 // SAFETY: Creating the layout is safe as long as merge_sort never calls this with an
846 // obscene length or 0.
848 alloc::alloc(alloc::Layout::array::<sort::TimSortRun>(len).unwrap_unchecked())
849 as *mut sort::TimSortRun
853 let run_dealloc_fn = |buf_ptr: *mut sort::TimSortRun, len: usize| {
854 // SAFETY: The caller must ensure that buf_ptr was created by elem_alloc_fn with the same
859 alloc::Layout::array::<sort::TimSortRun>(len).unwrap_unchecked(),
864 sort::merge_sort(v, &mut is_less, elem_alloc_fn, elem_dealloc_fn, run_alloc_fn, run_dealloc_fn);