core/slice/
mod.rs

1//! Slice management and manipulation.
2//!
3//! For more details see [`std::slice`].
4//!
5//! [`std::slice`]: ../../std/slice/index.html
6
7#![stable(feature = "rust1", since = "1.0.0")]
8
9use crate::cmp::Ordering::{self, Equal, Greater, Less};
10use crate::intrinsics::{exact_div, unchecked_sub};
11use crate::mem::{self, MaybeUninit, SizedTypeProperties};
12use crate::num::NonZero;
13use crate::ops::{OneSidedRange, OneSidedRangeBound, Range, RangeBounds, RangeInclusive};
14use crate::panic::const_panic;
15use crate::simd::{self, Simd};
16use crate::ub_checks::assert_unsafe_precondition;
17use crate::{fmt, hint, ptr, range, slice};
18
19#[unstable(
20    feature = "slice_internals",
21    issue = "none",
22    reason = "exposed from core to be reused in std; use the memchr crate"
23)]
24#[doc(hidden)]
25/// Pure Rust memchr implementation, taken from rust-memchr
26pub mod memchr;
27
28#[unstable(
29    feature = "slice_internals",
30    issue = "none",
31    reason = "exposed from core to be reused in std;"
32)]
33#[doc(hidden)]
34pub mod sort;
35
36mod ascii;
37mod cmp;
38pub(crate) mod index;
39mod iter;
40mod raw;
41mod rotate;
42mod specialize;
43
44#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
45pub use ascii::EscapeAscii;
46#[unstable(feature = "str_internals", issue = "none")]
47#[doc(hidden)]
48pub use ascii::is_ascii_simple;
49#[stable(feature = "slice_get_slice", since = "1.28.0")]
50pub use index::SliceIndex;
51#[unstable(feature = "slice_range", issue = "76393")]
52pub use index::{range, try_range};
53#[unstable(feature = "array_windows", issue = "75027")]
54pub use iter::ArrayWindows;
55#[unstable(feature = "array_chunks", issue = "74985")]
56pub use iter::{ArrayChunks, ArrayChunksMut};
57#[stable(feature = "slice_group_by", since = "1.77.0")]
58pub use iter::{ChunkBy, ChunkByMut};
59#[stable(feature = "rust1", since = "1.0.0")]
60pub use iter::{Chunks, ChunksMut, Windows};
61#[stable(feature = "chunks_exact", since = "1.31.0")]
62pub use iter::{ChunksExact, ChunksExactMut};
63#[stable(feature = "rust1", since = "1.0.0")]
64pub use iter::{Iter, IterMut};
65#[stable(feature = "rchunks", since = "1.31.0")]
66pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
67#[stable(feature = "slice_rsplit", since = "1.27.0")]
68pub use iter::{RSplit, RSplitMut};
69#[stable(feature = "rust1", since = "1.0.0")]
70pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
71#[stable(feature = "split_inclusive", since = "1.51.0")]
72pub use iter::{SplitInclusive, SplitInclusiveMut};
73#[stable(feature = "from_ref", since = "1.28.0")]
74pub use raw::{from_mut, from_ref};
75#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
76pub use raw::{from_mut_ptr_range, from_ptr_range};
77#[stable(feature = "rust1", since = "1.0.0")]
78pub use raw::{from_raw_parts, from_raw_parts_mut};
79
80/// Calculates the direction and split point of a one-sided range.
81///
82/// This is a helper function for `split_off` and `split_off_mut` that returns
83/// the direction of the split (front or back) as well as the index at
84/// which to split. Returns `None` if the split index would overflow.
85#[inline]
86fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {
87    use OneSidedRangeBound::{End, EndInclusive, StartInclusive};
88
89    Some(match range.bound() {
90        (StartInclusive, i) => (Direction::Back, i),
91        (End, i) => (Direction::Front, i),
92        (EndInclusive, i) => (Direction::Front, i.checked_add(1)?),
93    })
94}
95
96enum Direction {
97    Front,
98    Back,
99}
100
101impl<T> [T] {
102    /// Returns the number of elements in the slice.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// let a = [1, 2, 3];
108    /// assert_eq!(a.len(), 3);
109    /// ```
110    #[lang = "slice_len_fn"]
111    #[stable(feature = "rust1", since = "1.0.0")]
112    #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
113    #[rustc_no_implicit_autorefs]
114    #[inline]
115    #[must_use]
116    pub const fn len(&self) -> usize {
117        ptr::metadata(self)
118    }
119
120    /// Returns `true` if the slice has a length of 0.
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// let a = [1, 2, 3];
126    /// assert!(!a.is_empty());
127    ///
128    /// let b: &[i32] = &[];
129    /// assert!(b.is_empty());
130    /// ```
131    #[stable(feature = "rust1", since = "1.0.0")]
132    #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
133    #[rustc_no_implicit_autorefs]
134    #[inline]
135    #[must_use]
136    pub const fn is_empty(&self) -> bool {
137        self.len() == 0
138    }
139
140    /// Returns the first element of the slice, or `None` if it is empty.
141    ///
142    /// # Examples
143    ///
144    /// ```
145    /// let v = [10, 40, 30];
146    /// assert_eq!(Some(&10), v.first());
147    ///
148    /// let w: &[i32] = &[];
149    /// assert_eq!(None, w.first());
150    /// ```
151    #[stable(feature = "rust1", since = "1.0.0")]
152    #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
153    #[inline]
154    #[must_use]
155    pub const fn first(&self) -> Option<&T> {
156        if let [first, ..] = self { Some(first) } else { None }
157    }
158
159    /// Returns a mutable reference to the first element of the slice, or `None` if it is empty.
160    ///
161    /// # Examples
162    ///
163    /// ```
164    /// let x = &mut [0, 1, 2];
165    ///
166    /// if let Some(first) = x.first_mut() {
167    ///     *first = 5;
168    /// }
169    /// assert_eq!(x, &[5, 1, 2]);
170    ///
171    /// let y: &mut [i32] = &mut [];
172    /// assert_eq!(None, y.first_mut());
173    /// ```
174    #[stable(feature = "rust1", since = "1.0.0")]
175    #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
176    #[inline]
177    #[must_use]
178    pub const fn first_mut(&mut self) -> Option<&mut T> {
179        if let [first, ..] = self { Some(first) } else { None }
180    }
181
182    /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// let x = &[0, 1, 2];
188    ///
189    /// if let Some((first, elements)) = x.split_first() {
190    ///     assert_eq!(first, &0);
191    ///     assert_eq!(elements, &[1, 2]);
192    /// }
193    /// ```
194    #[stable(feature = "slice_splits", since = "1.5.0")]
195    #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
196    #[inline]
197    #[must_use]
198    pub const fn split_first(&self) -> Option<(&T, &[T])> {
199        if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
200    }
201
202    /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// let x = &mut [0, 1, 2];
208    ///
209    /// if let Some((first, elements)) = x.split_first_mut() {
210    ///     *first = 3;
211    ///     elements[0] = 4;
212    ///     elements[1] = 5;
213    /// }
214    /// assert_eq!(x, &[3, 4, 5]);
215    /// ```
216    #[stable(feature = "slice_splits", since = "1.5.0")]
217    #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
218    #[inline]
219    #[must_use]
220    pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
221        if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
222    }
223
224    /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// let x = &[0, 1, 2];
230    ///
231    /// if let Some((last, elements)) = x.split_last() {
232    ///     assert_eq!(last, &2);
233    ///     assert_eq!(elements, &[0, 1]);
234    /// }
235    /// ```
236    #[stable(feature = "slice_splits", since = "1.5.0")]
237    #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
238    #[inline]
239    #[must_use]
240    pub const fn split_last(&self) -> Option<(&T, &[T])> {
241        if let [init @ .., last] = self { Some((last, init)) } else { None }
242    }
243
244    /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// let x = &mut [0, 1, 2];
250    ///
251    /// if let Some((last, elements)) = x.split_last_mut() {
252    ///     *last = 3;
253    ///     elements[0] = 4;
254    ///     elements[1] = 5;
255    /// }
256    /// assert_eq!(x, &[4, 5, 3]);
257    /// ```
258    #[stable(feature = "slice_splits", since = "1.5.0")]
259    #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
260    #[inline]
261    #[must_use]
262    pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
263        if let [init @ .., last] = self { Some((last, init)) } else { None }
264    }
265
266    /// Returns the last element of the slice, or `None` if it is empty.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// let v = [10, 40, 30];
272    /// assert_eq!(Some(&30), v.last());
273    ///
274    /// let w: &[i32] = &[];
275    /// assert_eq!(None, w.last());
276    /// ```
277    #[stable(feature = "rust1", since = "1.0.0")]
278    #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
279    #[inline]
280    #[must_use]
281    pub const fn last(&self) -> Option<&T> {
282        if let [.., last] = self { Some(last) } else { None }
283    }
284
285    /// Returns a mutable reference to the last item in the slice, or `None` if it is empty.
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// let x = &mut [0, 1, 2];
291    ///
292    /// if let Some(last) = x.last_mut() {
293    ///     *last = 10;
294    /// }
295    /// assert_eq!(x, &[0, 1, 10]);
296    ///
297    /// let y: &mut [i32] = &mut [];
298    /// assert_eq!(None, y.last_mut());
299    /// ```
300    #[stable(feature = "rust1", since = "1.0.0")]
301    #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
302    #[inline]
303    #[must_use]
304    pub const fn last_mut(&mut self) -> Option<&mut T> {
305        if let [.., last] = self { Some(last) } else { None }
306    }
307
308    /// Returns an array reference to the first `N` items in the slice.
309    ///
310    /// If the slice is not at least `N` in length, this will return `None`.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// let u = [10, 40, 30];
316    /// assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
317    ///
318    /// let v: &[i32] = &[10];
319    /// assert_eq!(None, v.first_chunk::<2>());
320    ///
321    /// let w: &[i32] = &[];
322    /// assert_eq!(Some(&[]), w.first_chunk::<0>());
323    /// ```
324    #[inline]
325    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
326    #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
327    pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]> {
328        if self.len() < N {
329            None
330        } else {
331            // SAFETY: We explicitly check for the correct number of elements,
332            //   and do not let the reference outlive the slice.
333            Some(unsafe { &*(self.as_ptr().cast::<[T; N]>()) })
334        }
335    }
336
337    /// Returns a mutable array reference to the first `N` items in the slice.
338    ///
339    /// If the slice is not at least `N` in length, this will return `None`.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// let x = &mut [0, 1, 2];
345    ///
346    /// if let Some(first) = x.first_chunk_mut::<2>() {
347    ///     first[0] = 5;
348    ///     first[1] = 4;
349    /// }
350    /// assert_eq!(x, &[5, 4, 2]);
351    ///
352    /// assert_eq!(None, x.first_chunk_mut::<4>());
353    /// ```
354    #[inline]
355    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
356    #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
357    pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
358        if self.len() < N {
359            None
360        } else {
361            // SAFETY: We explicitly check for the correct number of elements,
362            //   do not let the reference outlive the slice,
363            //   and require exclusive access to the entire slice to mutate the chunk.
364            Some(unsafe { &mut *(self.as_mut_ptr().cast::<[T; N]>()) })
365        }
366    }
367
368    /// Returns an array reference to the first `N` items in the slice and the remaining slice.
369    ///
370    /// If the slice is not at least `N` in length, this will return `None`.
371    ///
372    /// # Examples
373    ///
374    /// ```
375    /// let x = &[0, 1, 2];
376    ///
377    /// if let Some((first, elements)) = x.split_first_chunk::<2>() {
378    ///     assert_eq!(first, &[0, 1]);
379    ///     assert_eq!(elements, &[2]);
380    /// }
381    ///
382    /// assert_eq!(None, x.split_first_chunk::<4>());
383    /// ```
384    #[inline]
385    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
386    #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
387    pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])> {
388        let Some((first, tail)) = self.split_at_checked(N) else { return None };
389
390        // SAFETY: We explicitly check for the correct number of elements,
391        //   and do not let the references outlive the slice.
392        Some((unsafe { &*(first.as_ptr().cast::<[T; N]>()) }, tail))
393    }
394
395    /// Returns a mutable array reference to the first `N` items in the slice and the remaining
396    /// slice.
397    ///
398    /// If the slice is not at least `N` in length, this will return `None`.
399    ///
400    /// # Examples
401    ///
402    /// ```
403    /// let x = &mut [0, 1, 2];
404    ///
405    /// if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
406    ///     first[0] = 3;
407    ///     first[1] = 4;
408    ///     elements[0] = 5;
409    /// }
410    /// assert_eq!(x, &[3, 4, 5]);
411    ///
412    /// assert_eq!(None, x.split_first_chunk_mut::<4>());
413    /// ```
414    #[inline]
415    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
416    #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
417    pub const fn split_first_chunk_mut<const N: usize>(
418        &mut self,
419    ) -> Option<(&mut [T; N], &mut [T])> {
420        let Some((first, tail)) = self.split_at_mut_checked(N) else { return None };
421
422        // SAFETY: We explicitly check for the correct number of elements,
423        //   do not let the reference outlive the slice,
424        //   and enforce exclusive mutability of the chunk by the split.
425        Some((unsafe { &mut *(first.as_mut_ptr().cast::<[T; N]>()) }, tail))
426    }
427
428    /// Returns an array reference to the last `N` items in the slice and the remaining slice.
429    ///
430    /// If the slice is not at least `N` in length, this will return `None`.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// let x = &[0, 1, 2];
436    ///
437    /// if let Some((elements, last)) = x.split_last_chunk::<2>() {
438    ///     assert_eq!(elements, &[0]);
439    ///     assert_eq!(last, &[1, 2]);
440    /// }
441    ///
442    /// assert_eq!(None, x.split_last_chunk::<4>());
443    /// ```
444    #[inline]
445    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
446    #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
447    pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])> {
448        let Some(index) = self.len().checked_sub(N) else { return None };
449        let (init, last) = self.split_at(index);
450
451        // SAFETY: We explicitly check for the correct number of elements,
452        //   and do not let the references outlive the slice.
453        Some((init, unsafe { &*(last.as_ptr().cast::<[T; N]>()) }))
454    }
455
456    /// Returns a mutable array reference to the last `N` items in the slice and the remaining
457    /// slice.
458    ///
459    /// If the slice is not at least `N` in length, this will return `None`.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// let x = &mut [0, 1, 2];
465    ///
466    /// if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
467    ///     last[0] = 3;
468    ///     last[1] = 4;
469    ///     elements[0] = 5;
470    /// }
471    /// assert_eq!(x, &[5, 3, 4]);
472    ///
473    /// assert_eq!(None, x.split_last_chunk_mut::<4>());
474    /// ```
475    #[inline]
476    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
477    #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
478    pub const fn split_last_chunk_mut<const N: usize>(
479        &mut self,
480    ) -> Option<(&mut [T], &mut [T; N])> {
481        let Some(index) = self.len().checked_sub(N) else { return None };
482        let (init, last) = self.split_at_mut(index);
483
484        // SAFETY: We explicitly check for the correct number of elements,
485        //   do not let the reference outlive the slice,
486        //   and enforce exclusive mutability of the chunk by the split.
487        Some((init, unsafe { &mut *(last.as_mut_ptr().cast::<[T; N]>()) }))
488    }
489
490    /// Returns an array reference to the last `N` items in the slice.
491    ///
492    /// If the slice is not at least `N` in length, this will return `None`.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// let u = [10, 40, 30];
498    /// assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
499    ///
500    /// let v: &[i32] = &[10];
501    /// assert_eq!(None, v.last_chunk::<2>());
502    ///
503    /// let w: &[i32] = &[];
504    /// assert_eq!(Some(&[]), w.last_chunk::<0>());
505    /// ```
506    #[inline]
507    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
508    #[rustc_const_stable(feature = "const_slice_last_chunk", since = "1.80.0")]
509    pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]> {
510        // FIXME(const-hack): Without const traits, we need this instead of `get`.
511        let Some(index) = self.len().checked_sub(N) else { return None };
512        let (_, last) = self.split_at(index);
513
514        // SAFETY: We explicitly check for the correct number of elements,
515        //   and do not let the references outlive the slice.
516        Some(unsafe { &*(last.as_ptr().cast::<[T; N]>()) })
517    }
518
519    /// Returns a mutable array reference to the last `N` items in the slice.
520    ///
521    /// If the slice is not at least `N` in length, this will return `None`.
522    ///
523    /// # Examples
524    ///
525    /// ```
526    /// let x = &mut [0, 1, 2];
527    ///
528    /// if let Some(last) = x.last_chunk_mut::<2>() {
529    ///     last[0] = 10;
530    ///     last[1] = 20;
531    /// }
532    /// assert_eq!(x, &[0, 10, 20]);
533    ///
534    /// assert_eq!(None, x.last_chunk_mut::<4>());
535    /// ```
536    #[inline]
537    #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
538    #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
539    pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
540        // FIXME(const-hack): Without const traits, we need this instead of `get`.
541        let Some(index) = self.len().checked_sub(N) else { return None };
542        let (_, last) = self.split_at_mut(index);
543
544        // SAFETY: We explicitly check for the correct number of elements,
545        //   do not let the reference outlive the slice,
546        //   and require exclusive access to the entire slice to mutate the chunk.
547        Some(unsafe { &mut *(last.as_mut_ptr().cast::<[T; N]>()) })
548    }
549
550    /// Returns a reference to an element or subslice depending on the type of
551    /// index.
552    ///
553    /// - If given a position, returns a reference to the element at that
554    ///   position or `None` if out of bounds.
555    /// - If given a range, returns the subslice corresponding to that range,
556    ///   or `None` if out of bounds.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// let v = [10, 40, 30];
562    /// assert_eq!(Some(&40), v.get(1));
563    /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
564    /// assert_eq!(None, v.get(3));
565    /// assert_eq!(None, v.get(0..4));
566    /// ```
567    #[stable(feature = "rust1", since = "1.0.0")]
568    #[rustc_no_implicit_autorefs]
569    #[inline]
570    #[must_use]
571    pub fn get<I>(&self, index: I) -> Option<&I::Output>
572    where
573        I: SliceIndex<Self>,
574    {
575        index.get(self)
576    }
577
578    /// Returns a mutable reference to an element or subslice depending on the
579    /// type of index (see [`get`]) or `None` if the index is out of bounds.
580    ///
581    /// [`get`]: slice::get
582    ///
583    /// # Examples
584    ///
585    /// ```
586    /// let x = &mut [0, 1, 2];
587    ///
588    /// if let Some(elem) = x.get_mut(1) {
589    ///     *elem = 42;
590    /// }
591    /// assert_eq!(x, &[0, 42, 2]);
592    /// ```
593    #[stable(feature = "rust1", since = "1.0.0")]
594    #[rustc_no_implicit_autorefs]
595    #[inline]
596    #[must_use]
597    pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
598    where
599        I: SliceIndex<Self>,
600    {
601        index.get_mut(self)
602    }
603
604    /// Returns a reference to an element or subslice, without doing bounds
605    /// checking.
606    ///
607    /// For a safe alternative see [`get`].
608    ///
609    /// # Safety
610    ///
611    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
612    /// even if the resulting reference is not used.
613    ///
614    /// You can think of this like `.get(index).unwrap_unchecked()`.  It's UB
615    /// to call `.get_unchecked(len)`, even if you immediately convert to a
616    /// pointer.  And it's UB to call `.get_unchecked(..len + 1)`,
617    /// `.get_unchecked(..=len)`, or similar.
618    ///
619    /// [`get`]: slice::get
620    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
621    ///
622    /// # Examples
623    ///
624    /// ```
625    /// let x = &[1, 2, 4];
626    ///
627    /// unsafe {
628    ///     assert_eq!(x.get_unchecked(1), &2);
629    /// }
630    /// ```
631    #[stable(feature = "rust1", since = "1.0.0")]
632    #[rustc_no_implicit_autorefs]
633    #[inline]
634    #[must_use]
635    #[track_caller]
636    pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
637    where
638        I: SliceIndex<Self>,
639    {
640        // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
641        // the slice is dereferenceable because `self` is a safe reference.
642        // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
643        unsafe { &*index.get_unchecked(self) }
644    }
645
646    /// Returns a mutable reference to an element or subslice, without doing
647    /// bounds checking.
648    ///
649    /// For a safe alternative see [`get_mut`].
650    ///
651    /// # Safety
652    ///
653    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
654    /// even if the resulting reference is not used.
655    ///
656    /// You can think of this like `.get_mut(index).unwrap_unchecked()`.  It's
657    /// UB to call `.get_unchecked_mut(len)`, even if you immediately convert
658    /// to a pointer.  And it's UB to call `.get_unchecked_mut(..len + 1)`,
659    /// `.get_unchecked_mut(..=len)`, or similar.
660    ///
661    /// [`get_mut`]: slice::get_mut
662    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
663    ///
664    /// # Examples
665    ///
666    /// ```
667    /// let x = &mut [1, 2, 4];
668    ///
669    /// unsafe {
670    ///     let elem = x.get_unchecked_mut(1);
671    ///     *elem = 13;
672    /// }
673    /// assert_eq!(x, &[1, 13, 4]);
674    /// ```
675    #[stable(feature = "rust1", since = "1.0.0")]
676    #[rustc_no_implicit_autorefs]
677    #[inline]
678    #[must_use]
679    #[track_caller]
680    pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
681    where
682        I: SliceIndex<Self>,
683    {
684        // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
685        // the slice is dereferenceable because `self` is a safe reference.
686        // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
687        unsafe { &mut *index.get_unchecked_mut(self) }
688    }
689
690    /// Returns a raw pointer to the slice's buffer.
691    ///
692    /// The caller must ensure that the slice outlives the pointer this
693    /// function returns, or else it will end up dangling.
694    ///
695    /// The caller must also ensure that the memory the pointer (non-transitively) points to
696    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
697    /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
698    ///
699    /// Modifying the container referenced by this slice may cause its buffer
700    /// to be reallocated, which would also make any pointers to it invalid.
701    ///
702    /// # Examples
703    ///
704    /// ```
705    /// let x = &[1, 2, 4];
706    /// let x_ptr = x.as_ptr();
707    ///
708    /// unsafe {
709    ///     for i in 0..x.len() {
710    ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
711    ///     }
712    /// }
713    /// ```
714    ///
715    /// [`as_mut_ptr`]: slice::as_mut_ptr
716    #[stable(feature = "rust1", since = "1.0.0")]
717    #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
718    #[rustc_never_returns_null_ptr]
719    #[rustc_as_ptr]
720    #[inline(always)]
721    #[must_use]
722    pub const fn as_ptr(&self) -> *const T {
723        self as *const [T] as *const T
724    }
725
726    /// Returns an unsafe mutable pointer to the slice's buffer.
727    ///
728    /// The caller must ensure that the slice outlives the pointer this
729    /// function returns, or else it will end up dangling.
730    ///
731    /// Modifying the container referenced by this slice may cause its buffer
732    /// to be reallocated, which would also make any pointers to it invalid.
733    ///
734    /// # Examples
735    ///
736    /// ```
737    /// let x = &mut [1, 2, 4];
738    /// let x_ptr = x.as_mut_ptr();
739    ///
740    /// unsafe {
741    ///     for i in 0..x.len() {
742    ///         *x_ptr.add(i) += 2;
743    ///     }
744    /// }
745    /// assert_eq!(x, &[3, 4, 6]);
746    /// ```
747    #[stable(feature = "rust1", since = "1.0.0")]
748    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
749    #[rustc_never_returns_null_ptr]
750    #[rustc_as_ptr]
751    #[inline(always)]
752    #[must_use]
753    pub const fn as_mut_ptr(&mut self) -> *mut T {
754        self as *mut [T] as *mut T
755    }
756
757    /// Returns the two raw pointers spanning the slice.
758    ///
759    /// The returned range is half-open, which means that the end pointer
760    /// points *one past* the last element of the slice. This way, an empty
761    /// slice is represented by two equal pointers, and the difference between
762    /// the two pointers represents the size of the slice.
763    ///
764    /// See [`as_ptr`] for warnings on using these pointers. The end pointer
765    /// requires extra caution, as it does not point to a valid element in the
766    /// slice.
767    ///
768    /// This function is useful for interacting with foreign interfaces which
769    /// use two pointers to refer to a range of elements in memory, as is
770    /// common in C++.
771    ///
772    /// It can also be useful to check if a pointer to an element refers to an
773    /// element of this slice:
774    ///
775    /// ```
776    /// let a = [1, 2, 3];
777    /// let x = &a[1] as *const _;
778    /// let y = &5 as *const _;
779    ///
780    /// assert!(a.as_ptr_range().contains(&x));
781    /// assert!(!a.as_ptr_range().contains(&y));
782    /// ```
783    ///
784    /// [`as_ptr`]: slice::as_ptr
785    #[stable(feature = "slice_ptr_range", since = "1.48.0")]
786    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
787    #[inline]
788    #[must_use]
789    pub const fn as_ptr_range(&self) -> Range<*const T> {
790        let start = self.as_ptr();
791        // SAFETY: The `add` here is safe, because:
792        //
793        //   - Both pointers are part of the same object, as pointing directly
794        //     past the object also counts.
795        //
796        //   - The size of the slice is never larger than `isize::MAX` bytes, as
797        //     noted here:
798        //       - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
799        //       - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
800        //       - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
801        //     (This doesn't seem normative yet, but the very same assumption is
802        //     made in many places, including the Index implementation of slices.)
803        //
804        //   - There is no wrapping around involved, as slices do not wrap past
805        //     the end of the address space.
806        //
807        // See the documentation of [`pointer::add`].
808        let end = unsafe { start.add(self.len()) };
809        start..end
810    }
811
812    /// Returns the two unsafe mutable pointers spanning the slice.
813    ///
814    /// The returned range is half-open, which means that the end pointer
815    /// points *one past* the last element of the slice. This way, an empty
816    /// slice is represented by two equal pointers, and the difference between
817    /// the two pointers represents the size of the slice.
818    ///
819    /// See [`as_mut_ptr`] for warnings on using these pointers. The end
820    /// pointer requires extra caution, as it does not point to a valid element
821    /// in the slice.
822    ///
823    /// This function is useful for interacting with foreign interfaces which
824    /// use two pointers to refer to a range of elements in memory, as is
825    /// common in C++.
826    ///
827    /// [`as_mut_ptr`]: slice::as_mut_ptr
828    #[stable(feature = "slice_ptr_range", since = "1.48.0")]
829    #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
830    #[inline]
831    #[must_use]
832    pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
833        let start = self.as_mut_ptr();
834        // SAFETY: See as_ptr_range() above for why `add` here is safe.
835        let end = unsafe { start.add(self.len()) };
836        start..end
837    }
838
839    /// Gets a reference to the underlying array.
840    ///
841    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
842    #[unstable(feature = "slice_as_array", issue = "133508")]
843    #[inline]
844    #[must_use]
845    pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]> {
846        if self.len() == N {
847            let ptr = self.as_ptr() as *const [T; N];
848
849            // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length.
850            let me = unsafe { &*ptr };
851            Some(me)
852        } else {
853            None
854        }
855    }
856
857    /// Gets a mutable reference to the slice's underlying array.
858    ///
859    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
860    #[unstable(feature = "slice_as_array", issue = "133508")]
861    #[inline]
862    #[must_use]
863    pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]> {
864        if self.len() == N {
865            let ptr = self.as_mut_ptr() as *mut [T; N];
866
867            // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length.
868            let me = unsafe { &mut *ptr };
869            Some(me)
870        } else {
871            None
872        }
873    }
874
875    /// Swaps two elements in the slice.
876    ///
877    /// If `a` equals to `b`, it's guaranteed that elements won't change value.
878    ///
879    /// # Arguments
880    ///
881    /// * a - The index of the first element
882    /// * b - The index of the second element
883    ///
884    /// # Panics
885    ///
886    /// Panics if `a` or `b` are out of bounds.
887    ///
888    /// # Examples
889    ///
890    /// ```
891    /// let mut v = ["a", "b", "c", "d", "e"];
892    /// v.swap(2, 4);
893    /// assert!(v == ["a", "b", "e", "d", "c"]);
894    /// ```
895    #[stable(feature = "rust1", since = "1.0.0")]
896    #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
897    #[inline]
898    #[track_caller]
899    pub const fn swap(&mut self, a: usize, b: usize) {
900        // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
901        // Can't take two mutable loans from one vector, so instead use raw pointers.
902        let pa = &raw mut self[a];
903        let pb = &raw mut self[b];
904        // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
905        // to elements in the slice and therefore are guaranteed to be valid and aligned.
906        // Note that accessing the elements behind `a` and `b` is checked and will
907        // panic when out of bounds.
908        unsafe {
909            ptr::swap(pa, pb);
910        }
911    }
912
913    /// Swaps two elements in the slice, without doing bounds checking.
914    ///
915    /// For a safe alternative see [`swap`].
916    ///
917    /// # Arguments
918    ///
919    /// * a - The index of the first element
920    /// * b - The index of the second element
921    ///
922    /// # Safety
923    ///
924    /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
925    /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
926    ///
927    /// # Examples
928    ///
929    /// ```
930    /// #![feature(slice_swap_unchecked)]
931    ///
932    /// let mut v = ["a", "b", "c", "d"];
933    /// // SAFETY: we know that 1 and 3 are both indices of the slice
934    /// unsafe { v.swap_unchecked(1, 3) };
935    /// assert!(v == ["a", "d", "c", "b"]);
936    /// ```
937    ///
938    /// [`swap`]: slice::swap
939    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
940    #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
941    #[track_caller]
942    pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
943        assert_unsafe_precondition!(
944            check_library_ub,
945            "slice::swap_unchecked requires that the indices are within the slice",
946            (
947                len: usize = self.len(),
948                a: usize = a,
949                b: usize = b,
950            ) => a < len && b < len,
951        );
952
953        let ptr = self.as_mut_ptr();
954        // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
955        unsafe {
956            ptr::swap(ptr.add(a), ptr.add(b));
957        }
958    }
959
960    /// Reverses the order of elements in the slice, in place.
961    ///
962    /// # Examples
963    ///
964    /// ```
965    /// let mut v = [1, 2, 3];
966    /// v.reverse();
967    /// assert!(v == [3, 2, 1]);
968    /// ```
969    #[stable(feature = "rust1", since = "1.0.0")]
970    #[rustc_const_unstable(feature = "const_slice_reverse", issue = "135120")]
971    #[inline]
972    pub const fn reverse(&mut self) {
973        let half_len = self.len() / 2;
974        let Range { start, end } = self.as_mut_ptr_range();
975
976        // These slices will skip the middle item for an odd length,
977        // since that one doesn't need to move.
978        let (front_half, back_half) =
979            // SAFETY: Both are subparts of the original slice, so the memory
980            // range is valid, and they don't overlap because they're each only
981            // half (or less) of the original slice.
982            unsafe {
983                (
984                    slice::from_raw_parts_mut(start, half_len),
985                    slice::from_raw_parts_mut(end.sub(half_len), half_len),
986                )
987            };
988
989        // Introducing a function boundary here means that the two halves
990        // get `noalias` markers, allowing better optimization as LLVM
991        // knows that they're disjoint, unlike in the original slice.
992        revswap(front_half, back_half, half_len);
993
994        #[inline]
995        const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
996            debug_assert!(a.len() == n);
997            debug_assert!(b.len() == n);
998
999            // Because this function is first compiled in isolation,
1000            // this check tells LLVM that the indexing below is
1001            // in-bounds. Then after inlining -- once the actual
1002            // lengths of the slices are known -- it's removed.
1003            let (a, _) = a.split_at_mut(n);
1004            let (b, _) = b.split_at_mut(n);
1005
1006            let mut i = 0;
1007            while i < n {
1008                mem::swap(&mut a[i], &mut b[n - 1 - i]);
1009                i += 1;
1010            }
1011        }
1012    }
1013
1014    /// Returns an iterator over the slice.
1015    ///
1016    /// The iterator yields all items from start to end.
1017    ///
1018    /// # Examples
1019    ///
1020    /// ```
1021    /// let x = &[1, 2, 4];
1022    /// let mut iterator = x.iter();
1023    ///
1024    /// assert_eq!(iterator.next(), Some(&1));
1025    /// assert_eq!(iterator.next(), Some(&2));
1026    /// assert_eq!(iterator.next(), Some(&4));
1027    /// assert_eq!(iterator.next(), None);
1028    /// ```
1029    #[stable(feature = "rust1", since = "1.0.0")]
1030    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1031    #[inline]
1032    #[rustc_diagnostic_item = "slice_iter"]
1033    pub const fn iter(&self) -> Iter<'_, T> {
1034        Iter::new(self)
1035    }
1036
1037    /// Returns an iterator that allows modifying each value.
1038    ///
1039    /// The iterator yields all items from start to end.
1040    ///
1041    /// # Examples
1042    ///
1043    /// ```
1044    /// let x = &mut [1, 2, 4];
1045    /// for elem in x.iter_mut() {
1046    ///     *elem += 2;
1047    /// }
1048    /// assert_eq!(x, &[3, 4, 6]);
1049    /// ```
1050    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1051    #[stable(feature = "rust1", since = "1.0.0")]
1052    #[inline]
1053    pub const fn iter_mut(&mut self) -> IterMut<'_, T> {
1054        IterMut::new(self)
1055    }
1056
1057    /// Returns an iterator over all contiguous windows of length
1058    /// `size`. The windows overlap. If the slice is shorter than
1059    /// `size`, the iterator returns no values.
1060    ///
1061    /// # Panics
1062    ///
1063    /// Panics if `size` is zero.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1069    /// let mut iter = slice.windows(3);
1070    /// assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
1071    /// assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
1072    /// assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
1073    /// assert!(iter.next().is_none());
1074    /// ```
1075    ///
1076    /// If the slice is shorter than `size`:
1077    ///
1078    /// ```
1079    /// let slice = ['f', 'o', 'o'];
1080    /// let mut iter = slice.windows(4);
1081    /// assert!(iter.next().is_none());
1082    /// ```
1083    ///
1084    /// Because the [Iterator] trait cannot represent the required lifetimes,
1085    /// there is no `windows_mut` analog to `windows`;
1086    /// `[0,1,2].windows_mut(2).collect()` would violate [the rules of references]
1087    /// (though a [LendingIterator] analog is possible). You can sometimes use
1088    /// [`Cell::as_slice_of_cells`](crate::cell::Cell::as_slice_of_cells) in
1089    /// conjunction with `windows` instead:
1090    ///
1091    /// [the rules of references]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references
1092    /// [LendingIterator]: https://blog.rust-lang.org/2022/10/28/gats-stabilization.html
1093    /// ```
1094    /// use std::cell::Cell;
1095    ///
1096    /// let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
1097    /// let slice = &mut array[..];
1098    /// let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
1099    /// for w in slice_of_cells.windows(3) {
1100    ///     Cell::swap(&w[0], &w[2]);
1101    /// }
1102    /// assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
1103    /// ```
1104    #[stable(feature = "rust1", since = "1.0.0")]
1105    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1106    #[inline]
1107    #[track_caller]
1108    pub const fn windows(&self, size: usize) -> Windows<'_, T> {
1109        let size = NonZero::new(size).expect("window size must be non-zero");
1110        Windows::new(self, size)
1111    }
1112
1113    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1114    /// beginning of the slice.
1115    ///
1116    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1117    /// slice, then the last chunk will not have length `chunk_size`.
1118    ///
1119    /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
1120    /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
1121    /// slice.
1122    ///
1123    /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will
1124    /// give references to arrays of exactly that length, rather than slices.
1125    ///
1126    /// # Panics
1127    ///
1128    /// Panics if `chunk_size` is zero.
1129    ///
1130    /// # Examples
1131    ///
1132    /// ```
1133    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1134    /// let mut iter = slice.chunks(2);
1135    /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1136    /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1137    /// assert_eq!(iter.next().unwrap(), &['m']);
1138    /// assert!(iter.next().is_none());
1139    /// ```
1140    ///
1141    /// [`chunks_exact`]: slice::chunks_exact
1142    /// [`rchunks`]: slice::rchunks
1143    /// [`as_chunks`]: slice::as_chunks
1144    #[stable(feature = "rust1", since = "1.0.0")]
1145    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1146    #[inline]
1147    #[track_caller]
1148    pub const fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
1149        assert!(chunk_size != 0, "chunk size must be non-zero");
1150        Chunks::new(self, chunk_size)
1151    }
1152
1153    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1154    /// beginning of the slice.
1155    ///
1156    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1157    /// length of the slice, then the last chunk will not have length `chunk_size`.
1158    ///
1159    /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
1160    /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
1161    /// the end of the slice.
1162    ///
1163    /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will
1164    /// give references to arrays of exactly that length, rather than slices.
1165    ///
1166    /// # Panics
1167    ///
1168    /// Panics if `chunk_size` is zero.
1169    ///
1170    /// # Examples
1171    ///
1172    /// ```
1173    /// let v = &mut [0, 0, 0, 0, 0];
1174    /// let mut count = 1;
1175    ///
1176    /// for chunk in v.chunks_mut(2) {
1177    ///     for elem in chunk.iter_mut() {
1178    ///         *elem += count;
1179    ///     }
1180    ///     count += 1;
1181    /// }
1182    /// assert_eq!(v, &[1, 1, 2, 2, 3]);
1183    /// ```
1184    ///
1185    /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1186    /// [`rchunks_mut`]: slice::rchunks_mut
1187    /// [`as_chunks_mut`]: slice::as_chunks_mut
1188    #[stable(feature = "rust1", since = "1.0.0")]
1189    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1190    #[inline]
1191    #[track_caller]
1192    pub const fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
1193        assert!(chunk_size != 0, "chunk size must be non-zero");
1194        ChunksMut::new(self, chunk_size)
1195    }
1196
1197    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1198    /// beginning of the slice.
1199    ///
1200    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1201    /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1202    /// from the `remainder` function of the iterator.
1203    ///
1204    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1205    /// resulting code better than in the case of [`chunks`].
1206    ///
1207    /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
1208    /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
1209    ///
1210    /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will
1211    /// give references to arrays of exactly that length, rather than slices.
1212    ///
1213    /// # Panics
1214    ///
1215    /// Panics if `chunk_size` is zero.
1216    ///
1217    /// # Examples
1218    ///
1219    /// ```
1220    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1221    /// let mut iter = slice.chunks_exact(2);
1222    /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1223    /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1224    /// assert!(iter.next().is_none());
1225    /// assert_eq!(iter.remainder(), &['m']);
1226    /// ```
1227    ///
1228    /// [`chunks`]: slice::chunks
1229    /// [`rchunks_exact`]: slice::rchunks_exact
1230    /// [`as_chunks`]: slice::chunks
1231    #[stable(feature = "chunks_exact", since = "1.31.0")]
1232    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1233    #[inline]
1234    #[track_caller]
1235    pub const fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
1236        assert!(chunk_size != 0, "chunk size must be non-zero");
1237        ChunksExact::new(self, chunk_size)
1238    }
1239
1240    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1241    /// beginning of the slice.
1242    ///
1243    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1244    /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1245    /// retrieved from the `into_remainder` function of the iterator.
1246    ///
1247    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1248    /// resulting code better than in the case of [`chunks_mut`].
1249    ///
1250    /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
1251    /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
1252    /// the slice.
1253    ///
1254    /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will
1255    /// give references to arrays of exactly that length, rather than slices.
1256    ///
1257    /// # Panics
1258    ///
1259    /// Panics if `chunk_size` is zero.
1260    ///
1261    /// # Examples
1262    ///
1263    /// ```
1264    /// let v = &mut [0, 0, 0, 0, 0];
1265    /// let mut count = 1;
1266    ///
1267    /// for chunk in v.chunks_exact_mut(2) {
1268    ///     for elem in chunk.iter_mut() {
1269    ///         *elem += count;
1270    ///     }
1271    ///     count += 1;
1272    /// }
1273    /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1274    /// ```
1275    ///
1276    /// [`chunks_mut`]: slice::chunks_mut
1277    /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1278    /// [`as_chunks_mut`]: slice::as_chunks_mut
1279    #[stable(feature = "chunks_exact", since = "1.31.0")]
1280    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1281    #[inline]
1282    #[track_caller]
1283    pub const fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
1284        assert!(chunk_size != 0, "chunk size must be non-zero");
1285        ChunksExactMut::new(self, chunk_size)
1286    }
1287
1288    /// Splits the slice into a slice of `N`-element arrays,
1289    /// assuming that there's no remainder.
1290    ///
1291    /// This is the inverse operation to [`as_flattened`].
1292    ///
1293    /// [`as_flattened`]: slice::as_flattened
1294    ///
1295    /// As this is `unsafe`, consider whether you could use [`as_chunks`] or
1296    /// [`as_rchunks`] instead, perhaps via something like
1297    /// `if let (chunks, []) = slice.as_chunks()` or
1298    /// `let (chunks, []) = slice.as_chunks() else { unreachable!() };`.
1299    ///
1300    /// [`as_chunks`]: slice::as_chunks
1301    /// [`as_rchunks`]: slice::as_rchunks
1302    ///
1303    /// # Safety
1304    ///
1305    /// This may only be called when
1306    /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1307    /// - `N != 0`.
1308    ///
1309    /// # Examples
1310    ///
1311    /// ```
1312    /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
1313    /// let chunks: &[[char; 1]] =
1314    ///     // SAFETY: 1-element chunks never have remainder
1315    ///     unsafe { slice.as_chunks_unchecked() };
1316    /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1317    /// let chunks: &[[char; 3]] =
1318    ///     // SAFETY: The slice length (6) is a multiple of 3
1319    ///     unsafe { slice.as_chunks_unchecked() };
1320    /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
1321    ///
1322    /// // These would be unsound:
1323    /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
1324    /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
1325    /// ```
1326    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1327    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1328    #[inline]
1329    #[must_use]
1330    #[track_caller]
1331    pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
1332        assert_unsafe_precondition!(
1333            check_language_ub,
1334            "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1335            (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n),
1336        );
1337        // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1338        let new_len = unsafe { exact_div(self.len(), N) };
1339        // SAFETY: We cast a slice of `new_len * N` elements into
1340        // a slice of `new_len` many `N` elements chunks.
1341        unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
1342    }
1343
1344    /// Splits the slice into a slice of `N`-element arrays,
1345    /// starting at the beginning of the slice,
1346    /// and a remainder slice with length strictly less than `N`.
1347    ///
1348    /// The remainder is meaningful in the division sense.  Given
1349    /// `let (chunks, remainder) = slice.as_chunks()`, then:
1350    /// - `chunks.len()` equals `slice.len() / N`,
1351    /// - `remainder.len()` equals `slice.len() % N`, and
1352    /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1353    ///
1354    /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].
1355    ///
1356    /// [`as_flattened`]: slice::as_flattened
1357    ///
1358    /// # Panics
1359    ///
1360    /// Panics if `N` is zero.
1361    ///
1362    /// Note that this check is against a const generic parameter, not a runtime
1363    /// value, and thus a particular monomorphization will either always panic
1364    /// or it will never panic.
1365    ///
1366    /// # Examples
1367    ///
1368    /// ```
1369    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1370    /// let (chunks, remainder) = slice.as_chunks();
1371    /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1372    /// assert_eq!(remainder, &['m']);
1373    /// ```
1374    ///
1375    /// If you expect the slice to be an exact multiple, you can combine
1376    /// `let`-`else` with an empty slice pattern:
1377    /// ```
1378    /// let slice = ['R', 'u', 's', 't'];
1379    /// let (chunks, []) = slice.as_chunks::<2>() else {
1380    ///     panic!("slice didn't have even length")
1381    /// };
1382    /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1383    /// ```
1384    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1385    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1386    #[inline]
1387    #[track_caller]
1388    #[must_use]
1389    pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1390        assert!(N != 0, "chunk size must be non-zero");
1391        let len_rounded_down = self.len() / N * N;
1392        // SAFETY: The rounded-down value is always the same or smaller than the
1393        // original length, and thus must be in-bounds of the slice.
1394        let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) };
1395        // SAFETY: We already panicked for zero, and ensured by construction
1396        // that the length of the subslice is a multiple of N.
1397        let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1398        (array_slice, remainder)
1399    }
1400
1401    /// Splits the slice into a slice of `N`-element arrays,
1402    /// starting at the end of the slice,
1403    /// and a remainder slice with length strictly less than `N`.
1404    ///
1405    /// The remainder is meaningful in the division sense.  Given
1406    /// `let (remainder, chunks) = slice.as_rchunks()`, then:
1407    /// - `remainder.len()` equals `slice.len() % N`,
1408    /// - `chunks.len()` equals `slice.len() / N`, and
1409    /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1410    ///
1411    /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].
1412    ///
1413    /// [`as_flattened`]: slice::as_flattened
1414    ///
1415    /// # Panics
1416    ///
1417    /// Panics if `N` is zero.
1418    ///
1419    /// Note that this check is against a const generic parameter, not a runtime
1420    /// value, and thus a particular monomorphization will either always panic
1421    /// or it will never panic.
1422    ///
1423    /// # Examples
1424    ///
1425    /// ```
1426    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1427    /// let (remainder, chunks) = slice.as_rchunks();
1428    /// assert_eq!(remainder, &['l']);
1429    /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1430    /// ```
1431    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1432    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1433    #[inline]
1434    #[track_caller]
1435    #[must_use]
1436    pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1437        assert!(N != 0, "chunk size must be non-zero");
1438        let len = self.len() / N;
1439        let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1440        // SAFETY: We already panicked for zero, and ensured by construction
1441        // that the length of the subslice is a multiple of N.
1442        let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1443        (remainder, array_slice)
1444    }
1445
1446    /// Returns an iterator over `N` elements of the slice at a time, starting at the
1447    /// beginning of the slice.
1448    ///
1449    /// The chunks are array references and do not overlap. If `N` does not divide the
1450    /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1451    /// retrieved from the `remainder` function of the iterator.
1452    ///
1453    /// This method is the const generic equivalent of [`chunks_exact`].
1454    ///
1455    /// # Panics
1456    ///
1457    /// Panics if `N` is zero. This check will most probably get changed to a compile time
1458    /// error before this method gets stabilized.
1459    ///
1460    /// # Examples
1461    ///
1462    /// ```
1463    /// #![feature(array_chunks)]
1464    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1465    /// let mut iter = slice.array_chunks();
1466    /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1467    /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1468    /// assert!(iter.next().is_none());
1469    /// assert_eq!(iter.remainder(), &['m']);
1470    /// ```
1471    ///
1472    /// [`chunks_exact`]: slice::chunks_exact
1473    #[unstable(feature = "array_chunks", issue = "74985")]
1474    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1475    #[inline]
1476    #[track_caller]
1477    pub const fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1478        assert!(N != 0, "chunk size must be non-zero");
1479        ArrayChunks::new(self)
1480    }
1481
1482    /// Splits the slice into a slice of `N`-element arrays,
1483    /// assuming that there's no remainder.
1484    ///
1485    /// This is the inverse operation to [`as_flattened_mut`].
1486    ///
1487    /// [`as_flattened_mut`]: slice::as_flattened_mut
1488    ///
1489    /// As this is `unsafe`, consider whether you could use [`as_chunks_mut`] or
1490    /// [`as_rchunks_mut`] instead, perhaps via something like
1491    /// `if let (chunks, []) = slice.as_chunks_mut()` or
1492    /// `let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };`.
1493    ///
1494    /// [`as_chunks_mut`]: slice::as_chunks_mut
1495    /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1496    ///
1497    /// # Safety
1498    ///
1499    /// This may only be called when
1500    /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1501    /// - `N != 0`.
1502    ///
1503    /// # Examples
1504    ///
1505    /// ```
1506    /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1507    /// let chunks: &mut [[char; 1]] =
1508    ///     // SAFETY: 1-element chunks never have remainder
1509    ///     unsafe { slice.as_chunks_unchecked_mut() };
1510    /// chunks[0] = ['L'];
1511    /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1512    /// let chunks: &mut [[char; 3]] =
1513    ///     // SAFETY: The slice length (6) is a multiple of 3
1514    ///     unsafe { slice.as_chunks_unchecked_mut() };
1515    /// chunks[1] = ['a', 'x', '?'];
1516    /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1517    ///
1518    /// // These would be unsound:
1519    /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1520    /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1521    /// ```
1522    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1523    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1524    #[inline]
1525    #[must_use]
1526    #[track_caller]
1527    pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1528        assert_unsafe_precondition!(
1529            check_language_ub,
1530            "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1531            (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n)
1532        );
1533        // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1534        let new_len = unsafe { exact_div(self.len(), N) };
1535        // SAFETY: We cast a slice of `new_len * N` elements into
1536        // a slice of `new_len` many `N` elements chunks.
1537        unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1538    }
1539
1540    /// Splits the slice into a slice of `N`-element arrays,
1541    /// starting at the beginning of the slice,
1542    /// and a remainder slice with length strictly less than `N`.
1543    ///
1544    /// The remainder is meaningful in the division sense.  Given
1545    /// `let (chunks, remainder) = slice.as_chunks_mut()`, then:
1546    /// - `chunks.len()` equals `slice.len() / N`,
1547    /// - `remainder.len()` equals `slice.len() % N`, and
1548    /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1549    ///
1550    /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].
1551    ///
1552    /// [`as_flattened_mut`]: slice::as_flattened_mut
1553    ///
1554    /// # Panics
1555    ///
1556    /// Panics if `N` is zero.
1557    ///
1558    /// Note that this check is against a const generic parameter, not a runtime
1559    /// value, and thus a particular monomorphization will either always panic
1560    /// or it will never panic.
1561    ///
1562    /// # Examples
1563    ///
1564    /// ```
1565    /// let v = &mut [0, 0, 0, 0, 0];
1566    /// let mut count = 1;
1567    ///
1568    /// let (chunks, remainder) = v.as_chunks_mut();
1569    /// remainder[0] = 9;
1570    /// for chunk in chunks {
1571    ///     *chunk = [count; 2];
1572    ///     count += 1;
1573    /// }
1574    /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1575    /// ```
1576    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1577    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1578    #[inline]
1579    #[track_caller]
1580    #[must_use]
1581    pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1582        assert!(N != 0, "chunk size must be non-zero");
1583        let len_rounded_down = self.len() / N * N;
1584        // SAFETY: The rounded-down value is always the same or smaller than the
1585        // original length, and thus must be in-bounds of the slice.
1586        let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) };
1587        // SAFETY: We already panicked for zero, and ensured by construction
1588        // that the length of the subslice is a multiple of N.
1589        let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1590        (array_slice, remainder)
1591    }
1592
1593    /// Splits the slice into a slice of `N`-element arrays,
1594    /// starting at the end of the slice,
1595    /// and a remainder slice with length strictly less than `N`.
1596    ///
1597    /// The remainder is meaningful in the division sense.  Given
1598    /// `let (remainder, chunks) = slice.as_rchunks_mut()`, then:
1599    /// - `remainder.len()` equals `slice.len() % N`,
1600    /// - `chunks.len()` equals `slice.len() / N`, and
1601    /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1602    ///
1603    /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].
1604    ///
1605    /// [`as_flattened_mut`]: slice::as_flattened_mut
1606    ///
1607    /// # Panics
1608    ///
1609    /// Panics if `N` is zero.
1610    ///
1611    /// Note that this check is against a const generic parameter, not a runtime
1612    /// value, and thus a particular monomorphization will either always panic
1613    /// or it will never panic.
1614    ///
1615    /// # Examples
1616    ///
1617    /// ```
1618    /// let v = &mut [0, 0, 0, 0, 0];
1619    /// let mut count = 1;
1620    ///
1621    /// let (remainder, chunks) = v.as_rchunks_mut();
1622    /// remainder[0] = 9;
1623    /// for chunk in chunks {
1624    ///     *chunk = [count; 2];
1625    ///     count += 1;
1626    /// }
1627    /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1628    /// ```
1629    #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1630    #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1631    #[inline]
1632    #[track_caller]
1633    #[must_use]
1634    pub const fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1635        assert!(N != 0, "chunk size must be non-zero");
1636        let len = self.len() / N;
1637        let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1638        // SAFETY: We already panicked for zero, and ensured by construction
1639        // that the length of the subslice is a multiple of N.
1640        let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1641        (remainder, array_slice)
1642    }
1643
1644    /// Returns an iterator over `N` elements of the slice at a time, starting at the
1645    /// beginning of the slice.
1646    ///
1647    /// The chunks are mutable array references and do not overlap. If `N` does not divide
1648    /// the length of the slice, then the last up to `N-1` elements will be omitted and
1649    /// can be retrieved from the `into_remainder` function of the iterator.
1650    ///
1651    /// This method is the const generic equivalent of [`chunks_exact_mut`].
1652    ///
1653    /// # Panics
1654    ///
1655    /// Panics if `N` is zero. This check will most probably get changed to a compile time
1656    /// error before this method gets stabilized.
1657    ///
1658    /// # Examples
1659    ///
1660    /// ```
1661    /// #![feature(array_chunks)]
1662    /// let v = &mut [0, 0, 0, 0, 0];
1663    /// let mut count = 1;
1664    ///
1665    /// for chunk in v.array_chunks_mut() {
1666    ///     *chunk = [count; 2];
1667    ///     count += 1;
1668    /// }
1669    /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1670    /// ```
1671    ///
1672    /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1673    #[unstable(feature = "array_chunks", issue = "74985")]
1674    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1675    #[inline]
1676    #[track_caller]
1677    pub const fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1678        assert!(N != 0, "chunk size must be non-zero");
1679        ArrayChunksMut::new(self)
1680    }
1681
1682    /// Returns an iterator over overlapping windows of `N` elements of a slice,
1683    /// starting at the beginning of the slice.
1684    ///
1685    /// This is the const generic equivalent of [`windows`].
1686    ///
1687    /// If `N` is greater than the size of the slice, it will return no windows.
1688    ///
1689    /// # Panics
1690    ///
1691    /// Panics if `N` is zero. This check will most probably get changed to a compile time
1692    /// error before this method gets stabilized.
1693    ///
1694    /// # Examples
1695    ///
1696    /// ```
1697    /// #![feature(array_windows)]
1698    /// let slice = [0, 1, 2, 3];
1699    /// let mut iter = slice.array_windows();
1700    /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1701    /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1702    /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1703    /// assert!(iter.next().is_none());
1704    /// ```
1705    ///
1706    /// [`windows`]: slice::windows
1707    #[unstable(feature = "array_windows", issue = "75027")]
1708    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1709    #[inline]
1710    #[track_caller]
1711    pub const fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1712        assert!(N != 0, "window size must be non-zero");
1713        ArrayWindows::new(self)
1714    }
1715
1716    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1717    /// of the slice.
1718    ///
1719    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1720    /// slice, then the last chunk will not have length `chunk_size`.
1721    ///
1722    /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1723    /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1724    /// of the slice.
1725    ///
1726    /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will
1727    /// give references to arrays of exactly that length, rather than slices.
1728    ///
1729    /// # Panics
1730    ///
1731    /// Panics if `chunk_size` is zero.
1732    ///
1733    /// # Examples
1734    ///
1735    /// ```
1736    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1737    /// let mut iter = slice.rchunks(2);
1738    /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1739    /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1740    /// assert_eq!(iter.next().unwrap(), &['l']);
1741    /// assert!(iter.next().is_none());
1742    /// ```
1743    ///
1744    /// [`rchunks_exact`]: slice::rchunks_exact
1745    /// [`chunks`]: slice::chunks
1746    /// [`as_rchunks`]: slice::as_rchunks
1747    #[stable(feature = "rchunks", since = "1.31.0")]
1748    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1749    #[inline]
1750    #[track_caller]
1751    pub const fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1752        assert!(chunk_size != 0, "chunk size must be non-zero");
1753        RChunks::new(self, chunk_size)
1754    }
1755
1756    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1757    /// of the slice.
1758    ///
1759    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1760    /// length of the slice, then the last chunk will not have length `chunk_size`.
1761    ///
1762    /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1763    /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1764    /// beginning of the slice.
1765    ///
1766    /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will
1767    /// give references to arrays of exactly that length, rather than slices.
1768    ///
1769    /// # Panics
1770    ///
1771    /// Panics if `chunk_size` is zero.
1772    ///
1773    /// # Examples
1774    ///
1775    /// ```
1776    /// let v = &mut [0, 0, 0, 0, 0];
1777    /// let mut count = 1;
1778    ///
1779    /// for chunk in v.rchunks_mut(2) {
1780    ///     for elem in chunk.iter_mut() {
1781    ///         *elem += count;
1782    ///     }
1783    ///     count += 1;
1784    /// }
1785    /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1786    /// ```
1787    ///
1788    /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1789    /// [`chunks_mut`]: slice::chunks_mut
1790    /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1791    #[stable(feature = "rchunks", since = "1.31.0")]
1792    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1793    #[inline]
1794    #[track_caller]
1795    pub const fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1796        assert!(chunk_size != 0, "chunk size must be non-zero");
1797        RChunksMut::new(self, chunk_size)
1798    }
1799
1800    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1801    /// end of the slice.
1802    ///
1803    /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1804    /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1805    /// from the `remainder` function of the iterator.
1806    ///
1807    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1808    /// resulting code better than in the case of [`rchunks`].
1809    ///
1810    /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1811    /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1812    /// slice.
1813    ///
1814    /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will
1815    /// give references to arrays of exactly that length, rather than slices.
1816    ///
1817    /// # Panics
1818    ///
1819    /// Panics if `chunk_size` is zero.
1820    ///
1821    /// # Examples
1822    ///
1823    /// ```
1824    /// let slice = ['l', 'o', 'r', 'e', 'm'];
1825    /// let mut iter = slice.rchunks_exact(2);
1826    /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1827    /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1828    /// assert!(iter.next().is_none());
1829    /// assert_eq!(iter.remainder(), &['l']);
1830    /// ```
1831    ///
1832    /// [`chunks`]: slice::chunks
1833    /// [`rchunks`]: slice::rchunks
1834    /// [`chunks_exact`]: slice::chunks_exact
1835    /// [`as_rchunks`]: slice::as_rchunks
1836    #[stable(feature = "rchunks", since = "1.31.0")]
1837    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1838    #[inline]
1839    #[track_caller]
1840    pub const fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1841        assert!(chunk_size != 0, "chunk size must be non-zero");
1842        RChunksExact::new(self, chunk_size)
1843    }
1844
1845    /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1846    /// of the slice.
1847    ///
1848    /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1849    /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1850    /// retrieved from the `into_remainder` function of the iterator.
1851    ///
1852    /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1853    /// resulting code better than in the case of [`chunks_mut`].
1854    ///
1855    /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1856    /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1857    /// of the slice.
1858    ///
1859    /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will
1860    /// give references to arrays of exactly that length, rather than slices.
1861    ///
1862    /// # Panics
1863    ///
1864    /// Panics if `chunk_size` is zero.
1865    ///
1866    /// # Examples
1867    ///
1868    /// ```
1869    /// let v = &mut [0, 0, 0, 0, 0];
1870    /// let mut count = 1;
1871    ///
1872    /// for chunk in v.rchunks_exact_mut(2) {
1873    ///     for elem in chunk.iter_mut() {
1874    ///         *elem += count;
1875    ///     }
1876    ///     count += 1;
1877    /// }
1878    /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1879    /// ```
1880    ///
1881    /// [`chunks_mut`]: slice::chunks_mut
1882    /// [`rchunks_mut`]: slice::rchunks_mut
1883    /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1884    /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1885    #[stable(feature = "rchunks", since = "1.31.0")]
1886    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1887    #[inline]
1888    #[track_caller]
1889    pub const fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1890        assert!(chunk_size != 0, "chunk size must be non-zero");
1891        RChunksExactMut::new(self, chunk_size)
1892    }
1893
1894    /// Returns an iterator over the slice producing non-overlapping runs
1895    /// of elements using the predicate to separate them.
1896    ///
1897    /// The predicate is called for every pair of consecutive elements,
1898    /// meaning that it is called on `slice[0]` and `slice[1]`,
1899    /// followed by `slice[1]` and `slice[2]`, and so on.
1900    ///
1901    /// # Examples
1902    ///
1903    /// ```
1904    /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1905    ///
1906    /// let mut iter = slice.chunk_by(|a, b| a == b);
1907    ///
1908    /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1909    /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1910    /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1911    /// assert_eq!(iter.next(), None);
1912    /// ```
1913    ///
1914    /// This method can be used to extract the sorted subslices:
1915    ///
1916    /// ```
1917    /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1918    ///
1919    /// let mut iter = slice.chunk_by(|a, b| a <= b);
1920    ///
1921    /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1922    /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1923    /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1924    /// assert_eq!(iter.next(), None);
1925    /// ```
1926    #[stable(feature = "slice_group_by", since = "1.77.0")]
1927    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1928    #[inline]
1929    pub const fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
1930    where
1931        F: FnMut(&T, &T) -> bool,
1932    {
1933        ChunkBy::new(self, pred)
1934    }
1935
1936    /// Returns an iterator over the slice producing non-overlapping mutable
1937    /// runs of elements using the predicate to separate them.
1938    ///
1939    /// The predicate is called for every pair of consecutive elements,
1940    /// meaning that it is called on `slice[0]` and `slice[1]`,
1941    /// followed by `slice[1]` and `slice[2]`, and so on.
1942    ///
1943    /// # Examples
1944    ///
1945    /// ```
1946    /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1947    ///
1948    /// let mut iter = slice.chunk_by_mut(|a, b| a == b);
1949    ///
1950    /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1951    /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1952    /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1953    /// assert_eq!(iter.next(), None);
1954    /// ```
1955    ///
1956    /// This method can be used to extract the sorted subslices:
1957    ///
1958    /// ```
1959    /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1960    ///
1961    /// let mut iter = slice.chunk_by_mut(|a, b| a <= b);
1962    ///
1963    /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1964    /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1965    /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1966    /// assert_eq!(iter.next(), None);
1967    /// ```
1968    #[stable(feature = "slice_group_by", since = "1.77.0")]
1969    #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1970    #[inline]
1971    pub const fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
1972    where
1973        F: FnMut(&T, &T) -> bool,
1974    {
1975        ChunkByMut::new(self, pred)
1976    }
1977
1978    /// Divides one slice into two at an index.
1979    ///
1980    /// The first will contain all indices from `[0, mid)` (excluding
1981    /// the index `mid` itself) and the second will contain all
1982    /// indices from `[mid, len)` (excluding the index `len` itself).
1983    ///
1984    /// # Panics
1985    ///
1986    /// Panics if `mid > len`.  For a non-panicking alternative see
1987    /// [`split_at_checked`](slice::split_at_checked).
1988    ///
1989    /// # Examples
1990    ///
1991    /// ```
1992    /// let v = ['a', 'b', 'c'];
1993    ///
1994    /// {
1995    ///    let (left, right) = v.split_at(0);
1996    ///    assert_eq!(left, []);
1997    ///    assert_eq!(right, ['a', 'b', 'c']);
1998    /// }
1999    ///
2000    /// {
2001    ///     let (left, right) = v.split_at(2);
2002    ///     assert_eq!(left, ['a', 'b']);
2003    ///     assert_eq!(right, ['c']);
2004    /// }
2005    ///
2006    /// {
2007    ///     let (left, right) = v.split_at(3);
2008    ///     assert_eq!(left, ['a', 'b', 'c']);
2009    ///     assert_eq!(right, []);
2010    /// }
2011    /// ```
2012    #[stable(feature = "rust1", since = "1.0.0")]
2013    #[rustc_const_stable(feature = "const_slice_split_at_not_mut", since = "1.71.0")]
2014    #[inline]
2015    #[track_caller]
2016    #[must_use]
2017    pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
2018        match self.split_at_checked(mid) {
2019            Some(pair) => pair,
2020            None => panic!("mid > len"),
2021        }
2022    }
2023
2024    /// Divides one mutable slice into two at an index.
2025    ///
2026    /// The first will contain all indices from `[0, mid)` (excluding
2027    /// the index `mid` itself) and the second will contain all
2028    /// indices from `[mid, len)` (excluding the index `len` itself).
2029    ///
2030    /// # Panics
2031    ///
2032    /// Panics if `mid > len`.  For a non-panicking alternative see
2033    /// [`split_at_mut_checked`](slice::split_at_mut_checked).
2034    ///
2035    /// # Examples
2036    ///
2037    /// ```
2038    /// let mut v = [1, 0, 3, 0, 5, 6];
2039    /// let (left, right) = v.split_at_mut(2);
2040    /// assert_eq!(left, [1, 0]);
2041    /// assert_eq!(right, [3, 0, 5, 6]);
2042    /// left[1] = 2;
2043    /// right[1] = 4;
2044    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2045    /// ```
2046    #[stable(feature = "rust1", since = "1.0.0")]
2047    #[inline]
2048    #[track_caller]
2049    #[must_use]
2050    #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2051    pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
2052        match self.split_at_mut_checked(mid) {
2053            Some(pair) => pair,
2054            None => panic!("mid > len"),
2055        }
2056    }
2057
2058    /// Divides one slice into two at an index, without doing bounds checking.
2059    ///
2060    /// The first will contain all indices from `[0, mid)` (excluding
2061    /// the index `mid` itself) and the second will contain all
2062    /// indices from `[mid, len)` (excluding the index `len` itself).
2063    ///
2064    /// For a safe alternative see [`split_at`].
2065    ///
2066    /// # Safety
2067    ///
2068    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2069    /// even if the resulting reference is not used. The caller has to ensure that
2070    /// `0 <= mid <= self.len()`.
2071    ///
2072    /// [`split_at`]: slice::split_at
2073    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2074    ///
2075    /// # Examples
2076    ///
2077    /// ```
2078    /// let v = ['a', 'b', 'c'];
2079    ///
2080    /// unsafe {
2081    ///    let (left, right) = v.split_at_unchecked(0);
2082    ///    assert_eq!(left, []);
2083    ///    assert_eq!(right, ['a', 'b', 'c']);
2084    /// }
2085    ///
2086    /// unsafe {
2087    ///     let (left, right) = v.split_at_unchecked(2);
2088    ///     assert_eq!(left, ['a', 'b']);
2089    ///     assert_eq!(right, ['c']);
2090    /// }
2091    ///
2092    /// unsafe {
2093    ///     let (left, right) = v.split_at_unchecked(3);
2094    ///     assert_eq!(left, ['a', 'b', 'c']);
2095    ///     assert_eq!(right, []);
2096    /// }
2097    /// ```
2098    #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
2099    #[rustc_const_stable(feature = "const_slice_split_at_unchecked", since = "1.77.0")]
2100    #[inline]
2101    #[must_use]
2102    #[track_caller]
2103    pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
2104        // FIXME(const-hack): the const function `from_raw_parts` is used to make this
2105        // function const; previously the implementation used
2106        // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
2107
2108        let len = self.len();
2109        let ptr = self.as_ptr();
2110
2111        assert_unsafe_precondition!(
2112            check_library_ub,
2113            "slice::split_at_unchecked requires the index to be within the slice",
2114            (mid: usize = mid, len: usize = len) => mid <= len,
2115        );
2116
2117        // SAFETY: Caller has to check that `0 <= mid <= self.len()`
2118        unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) }
2119    }
2120
2121    /// Divides one mutable slice into two at an index, without doing bounds checking.
2122    ///
2123    /// The first will contain all indices from `[0, mid)` (excluding
2124    /// the index `mid` itself) and the second will contain all
2125    /// indices from `[mid, len)` (excluding the index `len` itself).
2126    ///
2127    /// For a safe alternative see [`split_at_mut`].
2128    ///
2129    /// # Safety
2130    ///
2131    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2132    /// even if the resulting reference is not used. The caller has to ensure that
2133    /// `0 <= mid <= self.len()`.
2134    ///
2135    /// [`split_at_mut`]: slice::split_at_mut
2136    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2137    ///
2138    /// # Examples
2139    ///
2140    /// ```
2141    /// let mut v = [1, 0, 3, 0, 5, 6];
2142    /// // scoped to restrict the lifetime of the borrows
2143    /// unsafe {
2144    ///     let (left, right) = v.split_at_mut_unchecked(2);
2145    ///     assert_eq!(left, [1, 0]);
2146    ///     assert_eq!(right, [3, 0, 5, 6]);
2147    ///     left[1] = 2;
2148    ///     right[1] = 4;
2149    /// }
2150    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2151    /// ```
2152    #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
2153    #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2154    #[inline]
2155    #[must_use]
2156    #[track_caller]
2157    pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
2158        let len = self.len();
2159        let ptr = self.as_mut_ptr();
2160
2161        assert_unsafe_precondition!(
2162            check_library_ub,
2163            "slice::split_at_mut_unchecked requires the index to be within the slice",
2164            (mid: usize = mid, len: usize = len) => mid <= len,
2165        );
2166
2167        // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
2168        //
2169        // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
2170        // is fine.
2171        unsafe {
2172            (
2173                from_raw_parts_mut(ptr, mid),
2174                from_raw_parts_mut(ptr.add(mid), unchecked_sub(len, mid)),
2175            )
2176        }
2177    }
2178
2179    /// Divides one slice into two at an index, returning `None` if the slice is
2180    /// too short.
2181    ///
2182    /// If `mid ≤ len` returns a pair of slices where the first will contain all
2183    /// indices from `[0, mid)` (excluding the index `mid` itself) and the
2184    /// second will contain all indices from `[mid, len)` (excluding the index
2185    /// `len` itself).
2186    ///
2187    /// Otherwise, if `mid > len`, returns `None`.
2188    ///
2189    /// # Examples
2190    ///
2191    /// ```
2192    /// let v = [1, -2, 3, -4, 5, -6];
2193    ///
2194    /// {
2195    ///    let (left, right) = v.split_at_checked(0).unwrap();
2196    ///    assert_eq!(left, []);
2197    ///    assert_eq!(right, [1, -2, 3, -4, 5, -6]);
2198    /// }
2199    ///
2200    /// {
2201    ///     let (left, right) = v.split_at_checked(2).unwrap();
2202    ///     assert_eq!(left, [1, -2]);
2203    ///     assert_eq!(right, [3, -4, 5, -6]);
2204    /// }
2205    ///
2206    /// {
2207    ///     let (left, right) = v.split_at_checked(6).unwrap();
2208    ///     assert_eq!(left, [1, -2, 3, -4, 5, -6]);
2209    ///     assert_eq!(right, []);
2210    /// }
2211    ///
2212    /// assert_eq!(None, v.split_at_checked(7));
2213    /// ```
2214    #[stable(feature = "split_at_checked", since = "1.80.0")]
2215    #[rustc_const_stable(feature = "split_at_checked", since = "1.80.0")]
2216    #[inline]
2217    #[must_use]
2218    pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> {
2219        if mid <= self.len() {
2220            // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
2221            // fulfills the requirements of `split_at_unchecked`.
2222            Some(unsafe { self.split_at_unchecked(mid) })
2223        } else {
2224            None
2225        }
2226    }
2227
2228    /// Divides one mutable slice into two at an index, returning `None` if the
2229    /// slice is too short.
2230    ///
2231    /// If `mid ≤ len` returns a pair of slices where the first will contain all
2232    /// indices from `[0, mid)` (excluding the index `mid` itself) and the
2233    /// second will contain all indices from `[mid, len)` (excluding the index
2234    /// `len` itself).
2235    ///
2236    /// Otherwise, if `mid > len`, returns `None`.
2237    ///
2238    /// # Examples
2239    ///
2240    /// ```
2241    /// let mut v = [1, 0, 3, 0, 5, 6];
2242    ///
2243    /// if let Some((left, right)) = v.split_at_mut_checked(2) {
2244    ///     assert_eq!(left, [1, 0]);
2245    ///     assert_eq!(right, [3, 0, 5, 6]);
2246    ///     left[1] = 2;
2247    ///     right[1] = 4;
2248    /// }
2249    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2250    ///
2251    /// assert_eq!(None, v.split_at_mut_checked(7));
2252    /// ```
2253    #[stable(feature = "split_at_checked", since = "1.80.0")]
2254    #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2255    #[inline]
2256    #[must_use]
2257    pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut [T], &mut [T])> {
2258        if mid <= self.len() {
2259            // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
2260            // fulfills the requirements of `split_at_unchecked`.
2261            Some(unsafe { self.split_at_mut_unchecked(mid) })
2262        } else {
2263            None
2264        }
2265    }
2266
2267    /// Returns an iterator over subslices separated by elements that match
2268    /// `pred`. The matched element is not contained in the subslices.
2269    ///
2270    /// # Examples
2271    ///
2272    /// ```
2273    /// let slice = [10, 40, 33, 20];
2274    /// let mut iter = slice.split(|num| num % 3 == 0);
2275    ///
2276    /// assert_eq!(iter.next().unwrap(), &[10, 40]);
2277    /// assert_eq!(iter.next().unwrap(), &[20]);
2278    /// assert!(iter.next().is_none());
2279    /// ```
2280    ///
2281    /// If the first element is matched, an empty slice will be the first item
2282    /// returned by the iterator. Similarly, if the last element in the slice
2283    /// is matched, an empty slice will be the last item returned by the
2284    /// iterator:
2285    ///
2286    /// ```
2287    /// let slice = [10, 40, 33];
2288    /// let mut iter = slice.split(|num| num % 3 == 0);
2289    ///
2290    /// assert_eq!(iter.next().unwrap(), &[10, 40]);
2291    /// assert_eq!(iter.next().unwrap(), &[]);
2292    /// assert!(iter.next().is_none());
2293    /// ```
2294    ///
2295    /// If two matched elements are directly adjacent, an empty slice will be
2296    /// present between them:
2297    ///
2298    /// ```
2299    /// let slice = [10, 6, 33, 20];
2300    /// let mut iter = slice.split(|num| num % 3 == 0);
2301    ///
2302    /// assert_eq!(iter.next().unwrap(), &[10]);
2303    /// assert_eq!(iter.next().unwrap(), &[]);
2304    /// assert_eq!(iter.next().unwrap(), &[20]);
2305    /// assert!(iter.next().is_none());
2306    /// ```
2307    #[stable(feature = "rust1", since = "1.0.0")]
2308    #[inline]
2309    pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
2310    where
2311        F: FnMut(&T) -> bool,
2312    {
2313        Split::new(self, pred)
2314    }
2315
2316    /// Returns an iterator over mutable subslices separated by elements that
2317    /// match `pred`. The matched element is not contained in the subslices.
2318    ///
2319    /// # Examples
2320    ///
2321    /// ```
2322    /// let mut v = [10, 40, 30, 20, 60, 50];
2323    ///
2324    /// for group in v.split_mut(|num| *num % 3 == 0) {
2325    ///     group[0] = 1;
2326    /// }
2327    /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
2328    /// ```
2329    #[stable(feature = "rust1", since = "1.0.0")]
2330    #[inline]
2331    pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
2332    where
2333        F: FnMut(&T) -> bool,
2334    {
2335        SplitMut::new(self, pred)
2336    }
2337
2338    /// Returns an iterator over subslices separated by elements that match
2339    /// `pred`. The matched element is contained in the end of the previous
2340    /// subslice as a terminator.
2341    ///
2342    /// # Examples
2343    ///
2344    /// ```
2345    /// let slice = [10, 40, 33, 20];
2346    /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
2347    ///
2348    /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
2349    /// assert_eq!(iter.next().unwrap(), &[20]);
2350    /// assert!(iter.next().is_none());
2351    /// ```
2352    ///
2353    /// If the last element of the slice is matched,
2354    /// that element will be considered the terminator of the preceding slice.
2355    /// That slice will be the last item returned by the iterator.
2356    ///
2357    /// ```
2358    /// let slice = [3, 10, 40, 33];
2359    /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
2360    ///
2361    /// assert_eq!(iter.next().unwrap(), &[3]);
2362    /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
2363    /// assert!(iter.next().is_none());
2364    /// ```
2365    #[stable(feature = "split_inclusive", since = "1.51.0")]
2366    #[inline]
2367    pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
2368    where
2369        F: FnMut(&T) -> bool,
2370    {
2371        SplitInclusive::new(self, pred)
2372    }
2373
2374    /// Returns an iterator over mutable subslices separated by elements that
2375    /// match `pred`. The matched element is contained in the previous
2376    /// subslice as a terminator.
2377    ///
2378    /// # Examples
2379    ///
2380    /// ```
2381    /// let mut v = [10, 40, 30, 20, 60, 50];
2382    ///
2383    /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
2384    ///     let terminator_idx = group.len()-1;
2385    ///     group[terminator_idx] = 1;
2386    /// }
2387    /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
2388    /// ```
2389    #[stable(feature = "split_inclusive", since = "1.51.0")]
2390    #[inline]
2391    pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
2392    where
2393        F: FnMut(&T) -> bool,
2394    {
2395        SplitInclusiveMut::new(self, pred)
2396    }
2397
2398    /// Returns an iterator over subslices separated by elements that match
2399    /// `pred`, starting at the end of the slice and working backwards.
2400    /// The matched element is not contained in the subslices.
2401    ///
2402    /// # Examples
2403    ///
2404    /// ```
2405    /// let slice = [11, 22, 33, 0, 44, 55];
2406    /// let mut iter = slice.rsplit(|num| *num == 0);
2407    ///
2408    /// assert_eq!(iter.next().unwrap(), &[44, 55]);
2409    /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
2410    /// assert_eq!(iter.next(), None);
2411    /// ```
2412    ///
2413    /// As with `split()`, if the first or last element is matched, an empty
2414    /// slice will be the first (or last) item returned by the iterator.
2415    ///
2416    /// ```
2417    /// let v = &[0, 1, 1, 2, 3, 5, 8];
2418    /// let mut it = v.rsplit(|n| *n % 2 == 0);
2419    /// assert_eq!(it.next().unwrap(), &[]);
2420    /// assert_eq!(it.next().unwrap(), &[3, 5]);
2421    /// assert_eq!(it.next().unwrap(), &[1, 1]);
2422    /// assert_eq!(it.next().unwrap(), &[]);
2423    /// assert_eq!(it.next(), None);
2424    /// ```
2425    #[stable(feature = "slice_rsplit", since = "1.27.0")]
2426    #[inline]
2427    pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
2428    where
2429        F: FnMut(&T) -> bool,
2430    {
2431        RSplit::new(self, pred)
2432    }
2433
2434    /// Returns an iterator over mutable subslices separated by elements that
2435    /// match `pred`, starting at the end of the slice and working
2436    /// backwards. The matched element is not contained in the subslices.
2437    ///
2438    /// # Examples
2439    ///
2440    /// ```
2441    /// let mut v = [100, 400, 300, 200, 600, 500];
2442    ///
2443    /// let mut count = 0;
2444    /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
2445    ///     count += 1;
2446    ///     group[0] = count;
2447    /// }
2448    /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
2449    /// ```
2450    ///
2451    #[stable(feature = "slice_rsplit", since = "1.27.0")]
2452    #[inline]
2453    pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
2454    where
2455        F: FnMut(&T) -> bool,
2456    {
2457        RSplitMut::new(self, pred)
2458    }
2459
2460    /// Returns an iterator over subslices separated by elements that match
2461    /// `pred`, limited to returning at most `n` items. The matched element is
2462    /// not contained in the subslices.
2463    ///
2464    /// The last element returned, if any, will contain the remainder of the
2465    /// slice.
2466    ///
2467    /// # Examples
2468    ///
2469    /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
2470    /// `[20, 60, 50]`):
2471    ///
2472    /// ```
2473    /// let v = [10, 40, 30, 20, 60, 50];
2474    ///
2475    /// for group in v.splitn(2, |num| *num % 3 == 0) {
2476    ///     println!("{group:?}");
2477    /// }
2478    /// ```
2479    #[stable(feature = "rust1", since = "1.0.0")]
2480    #[inline]
2481    pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
2482    where
2483        F: FnMut(&T) -> bool,
2484    {
2485        SplitN::new(self.split(pred), n)
2486    }
2487
2488    /// Returns an iterator over mutable subslices separated by elements that match
2489    /// `pred`, limited to returning at most `n` items. The matched element is
2490    /// not contained in the subslices.
2491    ///
2492    /// The last element returned, if any, will contain the remainder of the
2493    /// slice.
2494    ///
2495    /// # Examples
2496    ///
2497    /// ```
2498    /// let mut v = [10, 40, 30, 20, 60, 50];
2499    ///
2500    /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
2501    ///     group[0] = 1;
2502    /// }
2503    /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
2504    /// ```
2505    #[stable(feature = "rust1", since = "1.0.0")]
2506    #[inline]
2507    pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
2508    where
2509        F: FnMut(&T) -> bool,
2510    {
2511        SplitNMut::new(self.split_mut(pred), n)
2512    }
2513
2514    /// Returns an iterator over subslices separated by elements that match
2515    /// `pred` limited to returning at most `n` items. This starts at the end of
2516    /// the slice and works backwards. The matched element is not contained in
2517    /// the subslices.
2518    ///
2519    /// The last element returned, if any, will contain the remainder of the
2520    /// slice.
2521    ///
2522    /// # Examples
2523    ///
2524    /// Print the slice split once, starting from the end, by numbers divisible
2525    /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
2526    ///
2527    /// ```
2528    /// let v = [10, 40, 30, 20, 60, 50];
2529    ///
2530    /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
2531    ///     println!("{group:?}");
2532    /// }
2533    /// ```
2534    #[stable(feature = "rust1", since = "1.0.0")]
2535    #[inline]
2536    pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
2537    where
2538        F: FnMut(&T) -> bool,
2539    {
2540        RSplitN::new(self.rsplit(pred), n)
2541    }
2542
2543    /// Returns an iterator over subslices separated by elements that match
2544    /// `pred` limited to returning at most `n` items. This starts at the end of
2545    /// the slice and works backwards. The matched element is not contained in
2546    /// the subslices.
2547    ///
2548    /// The last element returned, if any, will contain the remainder of the
2549    /// slice.
2550    ///
2551    /// # Examples
2552    ///
2553    /// ```
2554    /// let mut s = [10, 40, 30, 20, 60, 50];
2555    ///
2556    /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
2557    ///     group[0] = 1;
2558    /// }
2559    /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
2560    /// ```
2561    #[stable(feature = "rust1", since = "1.0.0")]
2562    #[inline]
2563    pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
2564    where
2565        F: FnMut(&T) -> bool,
2566    {
2567        RSplitNMut::new(self.rsplit_mut(pred), n)
2568    }
2569
2570    /// Splits the slice on the first element that matches the specified
2571    /// predicate.
2572    ///
2573    /// If any matching elements are present in the slice, returns the prefix
2574    /// before the match and suffix after. The matching element itself is not
2575    /// included. If no elements match, returns `None`.
2576    ///
2577    /// # Examples
2578    ///
2579    /// ```
2580    /// #![feature(slice_split_once)]
2581    /// let s = [1, 2, 3, 2, 4];
2582    /// assert_eq!(s.split_once(|&x| x == 2), Some((
2583    ///     &[1][..],
2584    ///     &[3, 2, 4][..]
2585    /// )));
2586    /// assert_eq!(s.split_once(|&x| x == 0), None);
2587    /// ```
2588    #[unstable(feature = "slice_split_once", reason = "newly added", issue = "112811")]
2589    #[inline]
2590    pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
2591    where
2592        F: FnMut(&T) -> bool,
2593    {
2594        let index = self.iter().position(pred)?;
2595        Some((&self[..index], &self[index + 1..]))
2596    }
2597
2598    /// Splits the slice on the last element that matches the specified
2599    /// predicate.
2600    ///
2601    /// If any matching elements are present in the slice, returns the prefix
2602    /// before the match and suffix after. The matching element itself is not
2603    /// included. If no elements match, returns `None`.
2604    ///
2605    /// # Examples
2606    ///
2607    /// ```
2608    /// #![feature(slice_split_once)]
2609    /// let s = [1, 2, 3, 2, 4];
2610    /// assert_eq!(s.rsplit_once(|&x| x == 2), Some((
2611    ///     &[1, 2, 3][..],
2612    ///     &[4][..]
2613    /// )));
2614    /// assert_eq!(s.rsplit_once(|&x| x == 0), None);
2615    /// ```
2616    #[unstable(feature = "slice_split_once", reason = "newly added", issue = "112811")]
2617    #[inline]
2618    pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
2619    where
2620        F: FnMut(&T) -> bool,
2621    {
2622        let index = self.iter().rposition(pred)?;
2623        Some((&self[..index], &self[index + 1..]))
2624    }
2625
2626    /// Returns `true` if the slice contains an element with the given value.
2627    ///
2628    /// This operation is *O*(*n*).
2629    ///
2630    /// Note that if you have a sorted slice, [`binary_search`] may be faster.
2631    ///
2632    /// [`binary_search`]: slice::binary_search
2633    ///
2634    /// # Examples
2635    ///
2636    /// ```
2637    /// let v = [10, 40, 30];
2638    /// assert!(v.contains(&30));
2639    /// assert!(!v.contains(&50));
2640    /// ```
2641    ///
2642    /// If you do not have a `&T`, but some other value that you can compare
2643    /// with one (for example, `String` implements `PartialEq<str>`), you can
2644    /// use `iter().any`:
2645    ///
2646    /// ```
2647    /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
2648    /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
2649    /// assert!(!v.iter().any(|e| e == "hi"));
2650    /// ```
2651    #[stable(feature = "rust1", since = "1.0.0")]
2652    #[inline]
2653    #[must_use]
2654    pub fn contains(&self, x: &T) -> bool
2655    where
2656        T: PartialEq,
2657    {
2658        cmp::SliceContains::slice_contains(x, self)
2659    }
2660
2661    /// Returns `true` if `needle` is a prefix of the slice or equal to the slice.
2662    ///
2663    /// # Examples
2664    ///
2665    /// ```
2666    /// let v = [10, 40, 30];
2667    /// assert!(v.starts_with(&[10]));
2668    /// assert!(v.starts_with(&[10, 40]));
2669    /// assert!(v.starts_with(&v));
2670    /// assert!(!v.starts_with(&[50]));
2671    /// assert!(!v.starts_with(&[10, 50]));
2672    /// ```
2673    ///
2674    /// Always returns `true` if `needle` is an empty slice:
2675    ///
2676    /// ```
2677    /// let v = &[10, 40, 30];
2678    /// assert!(v.starts_with(&[]));
2679    /// let v: &[u8] = &[];
2680    /// assert!(v.starts_with(&[]));
2681    /// ```
2682    #[stable(feature = "rust1", since = "1.0.0")]
2683    #[must_use]
2684    pub fn starts_with(&self, needle: &[T]) -> bool
2685    where
2686        T: PartialEq,
2687    {
2688        let n = needle.len();
2689        self.len() >= n && needle == &self[..n]
2690    }
2691
2692    /// Returns `true` if `needle` is a suffix of the slice or equal to the slice.
2693    ///
2694    /// # Examples
2695    ///
2696    /// ```
2697    /// let v = [10, 40, 30];
2698    /// assert!(v.ends_with(&[30]));
2699    /// assert!(v.ends_with(&[40, 30]));
2700    /// assert!(v.ends_with(&v));
2701    /// assert!(!v.ends_with(&[50]));
2702    /// assert!(!v.ends_with(&[50, 30]));
2703    /// ```
2704    ///
2705    /// Always returns `true` if `needle` is an empty slice:
2706    ///
2707    /// ```
2708    /// let v = &[10, 40, 30];
2709    /// assert!(v.ends_with(&[]));
2710    /// let v: &[u8] = &[];
2711    /// assert!(v.ends_with(&[]));
2712    /// ```
2713    #[stable(feature = "rust1", since = "1.0.0")]
2714    #[must_use]
2715    pub fn ends_with(&self, needle: &[T]) -> bool
2716    where
2717        T: PartialEq,
2718    {
2719        let (m, n) = (self.len(), needle.len());
2720        m >= n && needle == &self[m - n..]
2721    }
2722
2723    /// Returns a subslice with the prefix removed.
2724    ///
2725    /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2726    /// If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the
2727    /// original slice, returns an empty slice.
2728    ///
2729    /// If the slice does not start with `prefix`, returns `None`.
2730    ///
2731    /// # Examples
2732    ///
2733    /// ```
2734    /// let v = &[10, 40, 30];
2735    /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2736    /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2737    /// assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));
2738    /// assert_eq!(v.strip_prefix(&[50]), None);
2739    /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2740    ///
2741    /// let prefix : &str = "he";
2742    /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2743    ///            Some(b"llo".as_ref()));
2744    /// ```
2745    #[must_use = "returns the subslice without modifying the original"]
2746    #[stable(feature = "slice_strip", since = "1.51.0")]
2747    pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2748    where
2749        T: PartialEq,
2750    {
2751        // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2752        let prefix = prefix.as_slice();
2753        let n = prefix.len();
2754        if n <= self.len() {
2755            let (head, tail) = self.split_at(n);
2756            if head == prefix {
2757                return Some(tail);
2758            }
2759        }
2760        None
2761    }
2762
2763    /// Returns a subslice with the suffix removed.
2764    ///
2765    /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2766    /// If `suffix` is empty, simply returns the original slice. If `suffix` is equal to the
2767    /// original slice, returns an empty slice.
2768    ///
2769    /// If the slice does not end with `suffix`, returns `None`.
2770    ///
2771    /// # Examples
2772    ///
2773    /// ```
2774    /// let v = &[10, 40, 30];
2775    /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2776    /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2777    /// assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));
2778    /// assert_eq!(v.strip_suffix(&[50]), None);
2779    /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2780    /// ```
2781    #[must_use = "returns the subslice without modifying the original"]
2782    #[stable(feature = "slice_strip", since = "1.51.0")]
2783    pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2784    where
2785        T: PartialEq,
2786    {
2787        // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2788        let suffix = suffix.as_slice();
2789        let (len, n) = (self.len(), suffix.len());
2790        if n <= len {
2791            let (head, tail) = self.split_at(len - n);
2792            if tail == suffix {
2793                return Some(head);
2794            }
2795        }
2796        None
2797    }
2798
2799    /// Returns a subslice with the optional prefix removed.
2800    ///
2801    /// If the slice starts with `prefix`, returns the subslice after the prefix.  If `prefix`
2802    /// is empty or the slice does not start with `prefix`, simply returns the original slice.
2803    /// If `prefix` is equal to the original slice, returns an empty slice.
2804    ///
2805    /// # Examples
2806    ///
2807    /// ```
2808    /// #![feature(trim_prefix_suffix)]
2809    ///
2810    /// let v = &[10, 40, 30];
2811    ///
2812    /// // Prefix present - removes it
2813    /// assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);
2814    /// assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);
2815    /// assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);
2816    ///
2817    /// // Prefix absent - returns original slice
2818    /// assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);
2819    /// assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);
2820    ///
2821    /// let prefix : &str = "he";
2822    /// assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());
2823    /// ```
2824    #[must_use = "returns the subslice without modifying the original"]
2825    #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2826    pub fn trim_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> &[T]
2827    where
2828        T: PartialEq,
2829    {
2830        // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2831        let prefix = prefix.as_slice();
2832        let n = prefix.len();
2833        if n <= self.len() {
2834            let (head, tail) = self.split_at(n);
2835            if head == prefix {
2836                return tail;
2837            }
2838        }
2839        self
2840    }
2841
2842    /// Returns a subslice with the optional suffix removed.
2843    ///
2844    /// If the slice ends with `suffix`, returns the subslice before the suffix.  If `suffix`
2845    /// is empty or the slice does not end with `suffix`, simply returns the original slice.
2846    /// If `suffix` is equal to the original slice, returns an empty slice.
2847    ///
2848    /// # Examples
2849    ///
2850    /// ```
2851    /// #![feature(trim_prefix_suffix)]
2852    ///
2853    /// let v = &[10, 40, 30];
2854    ///
2855    /// // Suffix present - removes it
2856    /// assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);
2857    /// assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);
2858    /// assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);
2859    ///
2860    /// // Suffix absent - returns original slice
2861    /// assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);
2862    /// assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);
2863    /// ```
2864    #[must_use = "returns the subslice without modifying the original"]
2865    #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2866    pub fn trim_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> &[T]
2867    where
2868        T: PartialEq,
2869    {
2870        // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2871        let suffix = suffix.as_slice();
2872        let (len, n) = (self.len(), suffix.len());
2873        if n <= len {
2874            let (head, tail) = self.split_at(len - n);
2875            if tail == suffix {
2876                return head;
2877            }
2878        }
2879        self
2880    }
2881
2882    /// Binary searches this slice for a given element.
2883    /// If the slice is not sorted, the returned result is unspecified and
2884    /// meaningless.
2885    ///
2886    /// If the value is found then [`Result::Ok`] is returned, containing the
2887    /// index of the matching element. If there are multiple matches, then any
2888    /// one of the matches could be returned. The index is chosen
2889    /// deterministically, but is subject to change in future versions of Rust.
2890    /// If the value is not found then [`Result::Err`] is returned, containing
2891    /// the index where a matching element could be inserted while maintaining
2892    /// sorted order.
2893    ///
2894    /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2895    ///
2896    /// [`binary_search_by`]: slice::binary_search_by
2897    /// [`binary_search_by_key`]: slice::binary_search_by_key
2898    /// [`partition_point`]: slice::partition_point
2899    ///
2900    /// # Examples
2901    ///
2902    /// Looks up a series of four elements. The first is found, with a
2903    /// uniquely determined position; the second and third are not
2904    /// found; the fourth could match any position in `[1, 4]`.
2905    ///
2906    /// ```
2907    /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2908    ///
2909    /// assert_eq!(s.binary_search(&13),  Ok(9));
2910    /// assert_eq!(s.binary_search(&4),   Err(7));
2911    /// assert_eq!(s.binary_search(&100), Err(13));
2912    /// let r = s.binary_search(&1);
2913    /// assert!(match r { Ok(1..=4) => true, _ => false, });
2914    /// ```
2915    ///
2916    /// If you want to find that whole *range* of matching items, rather than
2917    /// an arbitrary matching one, that can be done using [`partition_point`]:
2918    /// ```
2919    /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2920    ///
2921    /// let low = s.partition_point(|x| x < &1);
2922    /// assert_eq!(low, 1);
2923    /// let high = s.partition_point(|x| x <= &1);
2924    /// assert_eq!(high, 5);
2925    /// let r = s.binary_search(&1);
2926    /// assert!((low..high).contains(&r.unwrap()));
2927    ///
2928    /// assert!(s[..low].iter().all(|&x| x < 1));
2929    /// assert!(s[low..high].iter().all(|&x| x == 1));
2930    /// assert!(s[high..].iter().all(|&x| x > 1));
2931    ///
2932    /// // For something not found, the "range" of equal items is empty
2933    /// assert_eq!(s.partition_point(|x| x < &11), 9);
2934    /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2935    /// assert_eq!(s.binary_search(&11), Err(9));
2936    /// ```
2937    ///
2938    /// If you want to insert an item to a sorted vector, while maintaining
2939    /// sort order, consider using [`partition_point`]:
2940    ///
2941    /// ```
2942    /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2943    /// let num = 42;
2944    /// let idx = s.partition_point(|&x| x <= num);
2945    /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2946    /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
2947    /// // to shift less elements.
2948    /// s.insert(idx, num);
2949    /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2950    /// ```
2951    #[stable(feature = "rust1", since = "1.0.0")]
2952    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2953    where
2954        T: Ord,
2955    {
2956        self.binary_search_by(|p| p.cmp(x))
2957    }
2958
2959    /// Binary searches this slice with a comparator function.
2960    ///
2961    /// The comparator function should return an order code that indicates
2962    /// whether its argument is `Less`, `Equal` or `Greater` the desired
2963    /// target.
2964    /// If the slice is not sorted or if the comparator function does not
2965    /// implement an order consistent with the sort order of the underlying
2966    /// slice, the returned result is unspecified and meaningless.
2967    ///
2968    /// If the value is found then [`Result::Ok`] is returned, containing the
2969    /// index of the matching element. If there are multiple matches, then any
2970    /// one of the matches could be returned. The index is chosen
2971    /// deterministically, but is subject to change in future versions of Rust.
2972    /// If the value is not found then [`Result::Err`] is returned, containing
2973    /// the index where a matching element could be inserted while maintaining
2974    /// sorted order.
2975    ///
2976    /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2977    ///
2978    /// [`binary_search`]: slice::binary_search
2979    /// [`binary_search_by_key`]: slice::binary_search_by_key
2980    /// [`partition_point`]: slice::partition_point
2981    ///
2982    /// # Examples
2983    ///
2984    /// Looks up a series of four elements. The first is found, with a
2985    /// uniquely determined position; the second and third are not
2986    /// found; the fourth could match any position in `[1, 4]`.
2987    ///
2988    /// ```
2989    /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2990    ///
2991    /// let seek = 13;
2992    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2993    /// let seek = 4;
2994    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2995    /// let seek = 100;
2996    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2997    /// let seek = 1;
2998    /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2999    /// assert!(match r { Ok(1..=4) => true, _ => false, });
3000    /// ```
3001    #[stable(feature = "rust1", since = "1.0.0")]
3002    #[inline]
3003    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
3004    where
3005        F: FnMut(&'a T) -> Ordering,
3006    {
3007        let mut size = self.len();
3008        if size == 0 {
3009            return Err(0);
3010        }
3011        let mut base = 0usize;
3012
3013        // This loop intentionally doesn't have an early exit if the comparison
3014        // returns Equal. We want the number of loop iterations to depend *only*
3015        // on the size of the input slice so that the CPU can reliably predict
3016        // the loop count.
3017        while size > 1 {
3018            let half = size / 2;
3019            let mid = base + half;
3020
3021            // SAFETY: the call is made safe by the following invariants:
3022            // - `mid >= 0`: by definition
3023            // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
3024            let cmp = f(unsafe { self.get_unchecked(mid) });
3025
3026            // Binary search interacts poorly with branch prediction, so force
3027            // the compiler to use conditional moves if supported by the target
3028            // architecture.
3029            base = hint::select_unpredictable(cmp == Greater, base, mid);
3030
3031            // This is imprecise in the case where `size` is odd and the
3032            // comparison returns Greater: the mid element still gets included
3033            // by `size` even though it's known to be larger than the element
3034            // being searched for.
3035            //
3036            // This is fine though: we gain more performance by keeping the
3037            // loop iteration count invariant (and thus predictable) than we
3038            // lose from considering one additional element.
3039            size -= half;
3040        }
3041
3042        // SAFETY: base is always in [0, size) because base <= mid.
3043        let cmp = f(unsafe { self.get_unchecked(base) });
3044        if cmp == Equal {
3045            // SAFETY: same as the `get_unchecked` above.
3046            unsafe { hint::assert_unchecked(base < self.len()) };
3047            Ok(base)
3048        } else {
3049            let result = base + (cmp == Less) as usize;
3050            // SAFETY: same as the `get_unchecked` above.
3051            // Note that this is `<=`, unlike the assume in the `Ok` path.
3052            unsafe { hint::assert_unchecked(result <= self.len()) };
3053            Err(result)
3054        }
3055    }
3056
3057    /// Binary searches this slice with a key extraction function.
3058    ///
3059    /// Assumes that the slice is sorted by the key, for instance with
3060    /// [`sort_by_key`] using the same key extraction function.
3061    /// If the slice is not sorted by the key, the returned result is
3062    /// unspecified and meaningless.
3063    ///
3064    /// If the value is found then [`Result::Ok`] is returned, containing the
3065    /// index of the matching element. If there are multiple matches, then any
3066    /// one of the matches could be returned. The index is chosen
3067    /// deterministically, but is subject to change in future versions of Rust.
3068    /// If the value is not found then [`Result::Err`] is returned, containing
3069    /// the index where a matching element could be inserted while maintaining
3070    /// sorted order.
3071    ///
3072    /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
3073    ///
3074    /// [`sort_by_key`]: slice::sort_by_key
3075    /// [`binary_search`]: slice::binary_search
3076    /// [`binary_search_by`]: slice::binary_search_by
3077    /// [`partition_point`]: slice::partition_point
3078    ///
3079    /// # Examples
3080    ///
3081    /// Looks up a series of four elements in a slice of pairs sorted by
3082    /// their second elements. The first is found, with a uniquely
3083    /// determined position; the second and third are not found; the
3084    /// fourth could match any position in `[1, 4]`.
3085    ///
3086    /// ```
3087    /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
3088    ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
3089    ///          (1, 21), (2, 34), (4, 55)];
3090    ///
3091    /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
3092    /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
3093    /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
3094    /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
3095    /// assert!(match r { Ok(1..=4) => true, _ => false, });
3096    /// ```
3097    // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
3098    // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
3099    // This breaks links when slice is displayed in core, but changing it to use relative links
3100    // would break when the item is re-exported. So allow the core links to be broken for now.
3101    #[allow(rustdoc::broken_intra_doc_links)]
3102    #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
3103    #[inline]
3104    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
3105    where
3106        F: FnMut(&'a T) -> B,
3107        B: Ord,
3108    {
3109        self.binary_search_by(|k| f(k).cmp(b))
3110    }
3111
3112    /// Sorts the slice in ascending order **without** preserving the initial order of equal elements.
3113    ///
3114    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3115    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3116    ///
3117    /// If the implementation of [`Ord`] for `T` does not implement a [total order], the function
3118    /// may panic; even if the function exits normally, the resulting order of elements in the slice
3119    /// is unspecified. See also the note on panicking below.
3120    ///
3121    /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3122    /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3123    /// examples see the [`Ord`] documentation.
3124    ///
3125    ///
3126    /// All original elements will remain in the slice and any possible modifications via interior
3127    /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `T` panics.
3128    ///
3129    /// Sorting types that only implement [`PartialOrd`] such as [`f32`] and [`f64`] require
3130    /// additional precautions. For example, `f32::NAN != f32::NAN`, which doesn't fulfill the
3131    /// reflexivity requirement of [`Ord`]. By using an alternative comparison function with
3132    /// `slice::sort_unstable_by` such as [`f32::total_cmp`] or [`f64::total_cmp`] that defines a
3133    /// [total order] users can sort slices containing floating-point values. Alternatively, if all
3134    /// values in the slice are guaranteed to be in a subset for which [`PartialOrd::partial_cmp`]
3135    /// forms a [total order], it's possible to sort the slice with `sort_unstable_by(|a, b|
3136    /// a.partial_cmp(b).unwrap())`.
3137    ///
3138    /// # Current implementation
3139    ///
3140    /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3141    /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3142    /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3143    /// expected time to sort the data is *O*(*n* \* log(*k*)).
3144    ///
3145    /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3146    /// slice is partially sorted.
3147    ///
3148    /// # Panics
3149    ///
3150    /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order], or if
3151    /// the [`Ord`] implementation panics.
3152    ///
3153    /// # Examples
3154    ///
3155    /// ```
3156    /// let mut v = [4, -5, 1, -3, 2];
3157    ///
3158    /// v.sort_unstable();
3159    /// assert_eq!(v, [-5, -3, 1, 2, 4]);
3160    /// ```
3161    ///
3162    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3163    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3164    #[stable(feature = "sort_unstable", since = "1.20.0")]
3165    #[inline]
3166    pub fn sort_unstable(&mut self)
3167    where
3168        T: Ord,
3169    {
3170        sort::unstable::sort(self, &mut T::lt);
3171    }
3172
3173    /// Sorts the slice in ascending order with a comparison function, **without** preserving the
3174    /// initial order of equal elements.
3175    ///
3176    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3177    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3178    ///
3179    /// If the comparison function `compare` does not implement a [total order], the function
3180    /// may panic; even if the function exits normally, the resulting order of elements in the slice
3181    /// is unspecified. See also the note on panicking below.
3182    ///
3183    /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3184    /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3185    /// examples see the [`Ord`] documentation.
3186    ///
3187    /// All original elements will remain in the slice and any possible modifications via interior
3188    /// mutability are observed in the input. Same is true if `compare` panics.
3189    ///
3190    /// # Current implementation
3191    ///
3192    /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3193    /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3194    /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3195    /// expected time to sort the data is *O*(*n* \* log(*k*)).
3196    ///
3197    /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3198    /// slice is partially sorted.
3199    ///
3200    /// # Panics
3201    ///
3202    /// May panic if the `compare` does not implement a [total order], or if
3203    /// the `compare` itself panics.
3204    ///
3205    /// # Examples
3206    ///
3207    /// ```
3208    /// let mut v = [4, -5, 1, -3, 2];
3209    /// v.sort_unstable_by(|a, b| a.cmp(b));
3210    /// assert_eq!(v, [-5, -3, 1, 2, 4]);
3211    ///
3212    /// // reverse sorting
3213    /// v.sort_unstable_by(|a, b| b.cmp(a));
3214    /// assert_eq!(v, [4, 2, 1, -3, -5]);
3215    /// ```
3216    ///
3217    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3218    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3219    #[stable(feature = "sort_unstable", since = "1.20.0")]
3220    #[inline]
3221    pub fn sort_unstable_by<F>(&mut self, mut compare: F)
3222    where
3223        F: FnMut(&T, &T) -> Ordering,
3224    {
3225        sort::unstable::sort(self, &mut |a, b| compare(a, b) == Ordering::Less);
3226    }
3227
3228    /// Sorts the slice in ascending order with a key extraction function, **without** preserving
3229    /// the initial order of equal elements.
3230    ///
3231    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3232    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3233    ///
3234    /// If the implementation of [`Ord`] for `K` does not implement a [total order], the function
3235    /// may panic; even if the function exits normally, the resulting order of elements in the slice
3236    /// is unspecified. See also the note on panicking below.
3237    ///
3238    /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3239    /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3240    /// examples see the [`Ord`] documentation.
3241    ///
3242    /// All original elements will remain in the slice and any possible modifications via interior
3243    /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `K` panics.
3244    ///
3245    /// # Current implementation
3246    ///
3247    /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3248    /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3249    /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3250    /// expected time to sort the data is *O*(*n* \* log(*k*)).
3251    ///
3252    /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3253    /// slice is partially sorted.
3254    ///
3255    /// # Panics
3256    ///
3257    /// May panic if the implementation of [`Ord`] for `K` does not implement a [total order], or if
3258    /// the [`Ord`] implementation panics.
3259    ///
3260    /// # Examples
3261    ///
3262    /// ```
3263    /// let mut v = [4i32, -5, 1, -3, 2];
3264    ///
3265    /// v.sort_unstable_by_key(|k| k.abs());
3266    /// assert_eq!(v, [1, 2, -3, 4, -5]);
3267    /// ```
3268    ///
3269    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3270    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3271    #[stable(feature = "sort_unstable", since = "1.20.0")]
3272    #[inline]
3273    pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
3274    where
3275        F: FnMut(&T) -> K,
3276        K: Ord,
3277    {
3278        sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b)));
3279    }
3280
3281    /// Reorders the slice such that the element at `index` is at a sort-order position. All
3282    /// elements before `index` will be `<=` to this value, and all elements after will be `>=` to
3283    /// it.
3284    ///
3285    /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3286    /// up at that position), in-place (i.e.  does not allocate), and runs in *O*(*n*) time. This
3287    /// function is also known as "kth element" in other libraries.
3288    ///
3289    /// Returns a triple that partitions the reordered slice:
3290    ///
3291    /// * The unsorted subslice before `index`, whose elements all satisfy `x <= self[index]`.
3292    ///
3293    /// * The element at `index`.
3294    ///
3295    /// * The unsorted subslice after `index`, whose elements all satisfy `x >= self[index]`.
3296    ///
3297    /// # Current implementation
3298    ///
3299    /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3300    /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3301    /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3302    /// for all inputs.
3303    ///
3304    /// [`sort_unstable`]: slice::sort_unstable
3305    ///
3306    /// # Panics
3307    ///
3308    /// Panics when `index >= len()`, and so always panics on empty slices.
3309    ///
3310    /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order].
3311    ///
3312    /// # Examples
3313    ///
3314    /// ```
3315    /// let mut v = [-5i32, 4, 2, -3, 1];
3316    ///
3317    /// // Find the items `<=` to the median, the median itself, and the items `>=` to it.
3318    /// let (lesser, median, greater) = v.select_nth_unstable(2);
3319    ///
3320    /// assert!(lesser == [-3, -5] || lesser == [-5, -3]);
3321    /// assert_eq!(median, &mut 1);
3322    /// assert!(greater == [4, 2] || greater == [2, 4]);
3323    ///
3324    /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3325    /// // about the specified index.
3326    /// assert!(v == [-3, -5, 1, 2, 4] ||
3327    ///         v == [-5, -3, 1, 2, 4] ||
3328    ///         v == [-3, -5, 1, 4, 2] ||
3329    ///         v == [-5, -3, 1, 4, 2]);
3330    /// ```
3331    ///
3332    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3333    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3334    #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3335    #[inline]
3336    pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
3337    where
3338        T: Ord,
3339    {
3340        sort::select::partition_at_index(self, index, T::lt)
3341    }
3342
3343    /// Reorders the slice with a comparator function such that the element at `index` is at a
3344    /// sort-order position. All elements before `index` will be `<=` to this value, and all
3345    /// elements after will be `>=` to it, according to the comparator function.
3346    ///
3347    /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3348    /// up at that position), in-place (i.e.  does not allocate), and runs in *O*(*n*) time. This
3349    /// function is also known as "kth element" in other libraries.
3350    ///
3351    /// Returns a triple partitioning the reordered slice:
3352    ///
3353    /// * The unsorted subslice before `index`, whose elements all satisfy
3354    ///   `compare(x, self[index]).is_le()`.
3355    ///
3356    /// * The element at `index`.
3357    ///
3358    /// * The unsorted subslice after `index`, whose elements all satisfy
3359    ///   `compare(x, self[index]).is_ge()`.
3360    ///
3361    /// # Current implementation
3362    ///
3363    /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3364    /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3365    /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3366    /// for all inputs.
3367    ///
3368    /// [`sort_unstable`]: slice::sort_unstable
3369    ///
3370    /// # Panics
3371    ///
3372    /// Panics when `index >= len()`, and so always panics on empty slices.
3373    ///
3374    /// May panic if `compare` does not implement a [total order].
3375    ///
3376    /// # Examples
3377    ///
3378    /// ```
3379    /// let mut v = [-5i32, 4, 2, -3, 1];
3380    ///
3381    /// // Find the items `>=` to the median, the median itself, and the items `<=` to it, by using
3382    /// // a reversed comparator.
3383    /// let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
3384    ///
3385    /// assert!(before == [4, 2] || before == [2, 4]);
3386    /// assert_eq!(median, &mut 1);
3387    /// assert!(after == [-3, -5] || after == [-5, -3]);
3388    ///
3389    /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3390    /// // about the specified index.
3391    /// assert!(v == [2, 4, 1, -5, -3] ||
3392    ///         v == [2, 4, 1, -3, -5] ||
3393    ///         v == [4, 2, 1, -5, -3] ||
3394    ///         v == [4, 2, 1, -3, -5]);
3395    /// ```
3396    ///
3397    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3398    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3399    #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3400    #[inline]
3401    pub fn select_nth_unstable_by<F>(
3402        &mut self,
3403        index: usize,
3404        mut compare: F,
3405    ) -> (&mut [T], &mut T, &mut [T])
3406    where
3407        F: FnMut(&T, &T) -> Ordering,
3408    {
3409        sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
3410    }
3411
3412    /// Reorders the slice with a key extraction function such that the element at `index` is at a
3413    /// sort-order position. All elements before `index` will have keys `<=` to the key at `index`,
3414    /// and all elements after will have keys `>=` to it.
3415    ///
3416    /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3417    /// up at that position), in-place (i.e.  does not allocate), and runs in *O*(*n*) time. This
3418    /// function is also known as "kth element" in other libraries.
3419    ///
3420    /// Returns a triple partitioning the reordered slice:
3421    ///
3422    /// * The unsorted subslice before `index`, whose elements all satisfy `f(x) <= f(self[index])`.
3423    ///
3424    /// * The element at `index`.
3425    ///
3426    /// * The unsorted subslice after `index`, whose elements all satisfy `f(x) >= f(self[index])`.
3427    ///
3428    /// # Current implementation
3429    ///
3430    /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3431    /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3432    /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3433    /// for all inputs.
3434    ///
3435    /// [`sort_unstable`]: slice::sort_unstable
3436    ///
3437    /// # Panics
3438    ///
3439    /// Panics when `index >= len()`, meaning it always panics on empty slices.
3440    ///
3441    /// May panic if `K: Ord` does not implement a total order.
3442    ///
3443    /// # Examples
3444    ///
3445    /// ```
3446    /// let mut v = [-5i32, 4, 1, -3, 2];
3447    ///
3448    /// // Find the items `<=` to the absolute median, the absolute median itself, and the items
3449    /// // `>=` to it.
3450    /// let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
3451    ///
3452    /// assert!(lesser == [1, 2] || lesser == [2, 1]);
3453    /// assert_eq!(median, &mut -3);
3454    /// assert!(greater == [4, -5] || greater == [-5, 4]);
3455    ///
3456    /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3457    /// // about the specified index.
3458    /// assert!(v == [1, 2, -3, 4, -5] ||
3459    ///         v == [1, 2, -3, -5, 4] ||
3460    ///         v == [2, 1, -3, 4, -5] ||
3461    ///         v == [2, 1, -3, -5, 4]);
3462    /// ```
3463    ///
3464    /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3465    /// [total order]: https://en.wikipedia.org/wiki/Total_order
3466    #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3467    #[inline]
3468    pub fn select_nth_unstable_by_key<K, F>(
3469        &mut self,
3470        index: usize,
3471        mut f: F,
3472    ) -> (&mut [T], &mut T, &mut [T])
3473    where
3474        F: FnMut(&T) -> K,
3475        K: Ord,
3476    {
3477        sort::select::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
3478    }
3479
3480    /// Moves all consecutive repeated elements to the end of the slice according to the
3481    /// [`PartialEq`] trait implementation.
3482    ///
3483    /// Returns two slices. The first contains no consecutive repeated elements.
3484    /// The second contains all the duplicates in no specified order.
3485    ///
3486    /// If the slice is sorted, the first returned slice contains no duplicates.
3487    ///
3488    /// # Examples
3489    ///
3490    /// ```
3491    /// #![feature(slice_partition_dedup)]
3492    ///
3493    /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
3494    ///
3495    /// let (dedup, duplicates) = slice.partition_dedup();
3496    ///
3497    /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
3498    /// assert_eq!(duplicates, [2, 3, 1]);
3499    /// ```
3500    #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3501    #[inline]
3502    pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
3503    where
3504        T: PartialEq,
3505    {
3506        self.partition_dedup_by(|a, b| a == b)
3507    }
3508
3509    /// Moves all but the first of consecutive elements to the end of the slice satisfying
3510    /// a given equality relation.
3511    ///
3512    /// Returns two slices. The first contains no consecutive repeated elements.
3513    /// The second contains all the duplicates in no specified order.
3514    ///
3515    /// The `same_bucket` function is passed references to two elements from the slice and
3516    /// must determine if the elements compare equal. The elements are passed in opposite order
3517    /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
3518    /// at the end of the slice.
3519    ///
3520    /// If the slice is sorted, the first returned slice contains no duplicates.
3521    ///
3522    /// # Examples
3523    ///
3524    /// ```
3525    /// #![feature(slice_partition_dedup)]
3526    ///
3527    /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
3528    ///
3529    /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
3530    ///
3531    /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
3532    /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
3533    /// ```
3534    #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3535    #[inline]
3536    pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
3537    where
3538        F: FnMut(&mut T, &mut T) -> bool,
3539    {
3540        // Although we have a mutable reference to `self`, we cannot make
3541        // *arbitrary* changes. The `same_bucket` calls could panic, so we
3542        // must ensure that the slice is in a valid state at all times.
3543        //
3544        // The way that we handle this is by using swaps; we iterate
3545        // over all the elements, swapping as we go so that at the end
3546        // the elements we wish to keep are in the front, and those we
3547        // wish to reject are at the back. We can then split the slice.
3548        // This operation is still `O(n)`.
3549        //
3550        // Example: We start in this state, where `r` represents "next
3551        // read" and `w` represents "next_write".
3552        //
3553        //           r
3554        //     +---+---+---+---+---+---+
3555        //     | 0 | 1 | 1 | 2 | 3 | 3 |
3556        //     +---+---+---+---+---+---+
3557        //           w
3558        //
3559        // Comparing self[r] against self[w-1], this is not a duplicate, so
3560        // we swap self[r] and self[w] (no effect as r==w) and then increment both
3561        // r and w, leaving us with:
3562        //
3563        //               r
3564        //     +---+---+---+---+---+---+
3565        //     | 0 | 1 | 1 | 2 | 3 | 3 |
3566        //     +---+---+---+---+---+---+
3567        //               w
3568        //
3569        // Comparing self[r] against self[w-1], this value is a duplicate,
3570        // so we increment `r` but leave everything else unchanged:
3571        //
3572        //                   r
3573        //     +---+---+---+---+---+---+
3574        //     | 0 | 1 | 1 | 2 | 3 | 3 |
3575        //     +---+---+---+---+---+---+
3576        //               w
3577        //
3578        // Comparing self[r] against self[w-1], this is not a duplicate,
3579        // so swap self[r] and self[w] and advance r and w:
3580        //
3581        //                       r
3582        //     +---+---+---+---+---+---+
3583        //     | 0 | 1 | 2 | 1 | 3 | 3 |
3584        //     +---+---+---+---+---+---+
3585        //                   w
3586        //
3587        // Not a duplicate, repeat:
3588        //
3589        //                           r
3590        //     +---+---+---+---+---+---+
3591        //     | 0 | 1 | 2 | 3 | 1 | 3 |
3592        //     +---+---+---+---+---+---+
3593        //                       w
3594        //
3595        // Duplicate, advance r. End of slice. Split at w.
3596
3597        let len = self.len();
3598        if len <= 1 {
3599            return (self, &mut []);
3600        }
3601
3602        let ptr = self.as_mut_ptr();
3603        let mut next_read: usize = 1;
3604        let mut next_write: usize = 1;
3605
3606        // SAFETY: the `while` condition guarantees `next_read` and `next_write`
3607        // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
3608        // one element before `ptr_write`, but `next_write` starts at 1, so
3609        // `prev_ptr_write` is never less than 0 and is inside the slice.
3610        // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
3611        // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
3612        // and `prev_ptr_write.offset(1)`.
3613        //
3614        // `next_write` is also incremented at most once per loop at most meaning
3615        // no element is skipped when it may need to be swapped.
3616        //
3617        // `ptr_read` and `prev_ptr_write` never point to the same element. This
3618        // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
3619        // The explanation is simply that `next_read >= next_write` is always true,
3620        // thus `next_read > next_write - 1` is too.
3621        unsafe {
3622            // Avoid bounds checks by using raw pointers.
3623            while next_read < len {
3624                let ptr_read = ptr.add(next_read);
3625                let prev_ptr_write = ptr.add(next_write - 1);
3626                if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
3627                    if next_read != next_write {
3628                        let ptr_write = prev_ptr_write.add(1);
3629                        mem::swap(&mut *ptr_read, &mut *ptr_write);
3630                    }
3631                    next_write += 1;
3632                }
3633                next_read += 1;
3634            }
3635        }
3636
3637        self.split_at_mut(next_write)
3638    }
3639
3640    /// Moves all but the first of consecutive elements to the end of the slice that resolve
3641    /// to the same key.
3642    ///
3643    /// Returns two slices. The first contains no consecutive repeated elements.
3644    /// The second contains all the duplicates in no specified order.
3645    ///
3646    /// If the slice is sorted, the first returned slice contains no duplicates.
3647    ///
3648    /// # Examples
3649    ///
3650    /// ```
3651    /// #![feature(slice_partition_dedup)]
3652    ///
3653    /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3654    ///
3655    /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3656    ///
3657    /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3658    /// assert_eq!(duplicates, [21, 30, 13]);
3659    /// ```
3660    #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3661    #[inline]
3662    pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3663    where
3664        F: FnMut(&mut T) -> K,
3665        K: PartialEq,
3666    {
3667        self.partition_dedup_by(|a, b| key(a) == key(b))
3668    }
3669
3670    /// Rotates the slice in-place such that the first `mid` elements of the
3671    /// slice move to the end while the last `self.len() - mid` elements move to
3672    /// the front.
3673    ///
3674    /// After calling `rotate_left`, the element previously at index `mid` will
3675    /// become the first element in the slice.
3676    ///
3677    /// # Panics
3678    ///
3679    /// This function will panic if `mid` is greater than the length of the
3680    /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3681    /// rotation.
3682    ///
3683    /// # Complexity
3684    ///
3685    /// Takes linear (in `self.len()`) time.
3686    ///
3687    /// # Examples
3688    ///
3689    /// ```
3690    /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3691    /// a.rotate_left(2);
3692    /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3693    /// ```
3694    ///
3695    /// Rotating a subslice:
3696    ///
3697    /// ```
3698    /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3699    /// a[1..5].rotate_left(1);
3700    /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3701    /// ```
3702    #[stable(feature = "slice_rotate", since = "1.26.0")]
3703    #[rustc_const_unstable(feature = "const_slice_rotate", issue = "143812")]
3704    pub const fn rotate_left(&mut self, mid: usize) {
3705        assert!(mid <= self.len());
3706        let k = self.len() - mid;
3707        let p = self.as_mut_ptr();
3708
3709        // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3710        // valid for reading and writing, as required by `ptr_rotate`.
3711        unsafe {
3712            rotate::ptr_rotate(mid, p.add(mid), k);
3713        }
3714    }
3715
3716    /// Rotates the slice in-place such that the first `self.len() - k`
3717    /// elements of the slice move to the end while the last `k` elements move
3718    /// to the front.
3719    ///
3720    /// After calling `rotate_right`, the element previously at index
3721    /// `self.len() - k` will become the first element in the slice.
3722    ///
3723    /// # Panics
3724    ///
3725    /// This function will panic if `k` is greater than the length of the
3726    /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3727    /// rotation.
3728    ///
3729    /// # Complexity
3730    ///
3731    /// Takes linear (in `self.len()`) time.
3732    ///
3733    /// # Examples
3734    ///
3735    /// ```
3736    /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3737    /// a.rotate_right(2);
3738    /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3739    /// ```
3740    ///
3741    /// Rotating a subslice:
3742    ///
3743    /// ```
3744    /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3745    /// a[1..5].rotate_right(1);
3746    /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3747    /// ```
3748    #[stable(feature = "slice_rotate", since = "1.26.0")]
3749    #[rustc_const_unstable(feature = "const_slice_rotate", issue = "143812")]
3750    pub const fn rotate_right(&mut self, k: usize) {
3751        assert!(k <= self.len());
3752        let mid = self.len() - k;
3753        let p = self.as_mut_ptr();
3754
3755        // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3756        // valid for reading and writing, as required by `ptr_rotate`.
3757        unsafe {
3758            rotate::ptr_rotate(mid, p.add(mid), k);
3759        }
3760    }
3761
3762    /// Fills `self` with elements by cloning `value`.
3763    ///
3764    /// # Examples
3765    ///
3766    /// ```
3767    /// let mut buf = vec![0; 10];
3768    /// buf.fill(1);
3769    /// assert_eq!(buf, vec![1; 10]);
3770    /// ```
3771    #[doc(alias = "memset")]
3772    #[stable(feature = "slice_fill", since = "1.50.0")]
3773    pub fn fill(&mut self, value: T)
3774    where
3775        T: Clone,
3776    {
3777        specialize::SpecFill::spec_fill(self, value);
3778    }
3779
3780    /// Fills `self` with elements returned by calling a closure repeatedly.
3781    ///
3782    /// This method uses a closure to create new values. If you'd rather
3783    /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3784    /// trait to generate values, you can pass [`Default::default`] as the
3785    /// argument.
3786    ///
3787    /// [`fill`]: slice::fill
3788    ///
3789    /// # Examples
3790    ///
3791    /// ```
3792    /// let mut buf = vec![1; 10];
3793    /// buf.fill_with(Default::default);
3794    /// assert_eq!(buf, vec![0; 10]);
3795    /// ```
3796    #[stable(feature = "slice_fill_with", since = "1.51.0")]
3797    pub fn fill_with<F>(&mut self, mut f: F)
3798    where
3799        F: FnMut() -> T,
3800    {
3801        for el in self {
3802            *el = f();
3803        }
3804    }
3805
3806    /// Copies the elements from `src` into `self`.
3807    ///
3808    /// The length of `src` must be the same as `self`.
3809    ///
3810    /// # Panics
3811    ///
3812    /// This function will panic if the two slices have different lengths.
3813    ///
3814    /// # Examples
3815    ///
3816    /// Cloning two elements from a slice into another:
3817    ///
3818    /// ```
3819    /// let src = [1, 2, 3, 4];
3820    /// let mut dst = [0, 0];
3821    ///
3822    /// // Because the slices have to be the same length,
3823    /// // we slice the source slice from four elements
3824    /// // to two. It will panic if we don't do this.
3825    /// dst.clone_from_slice(&src[2..]);
3826    ///
3827    /// assert_eq!(src, [1, 2, 3, 4]);
3828    /// assert_eq!(dst, [3, 4]);
3829    /// ```
3830    ///
3831    /// Rust enforces that there can only be one mutable reference with no
3832    /// immutable references to a particular piece of data in a particular
3833    /// scope. Because of this, attempting to use `clone_from_slice` on a
3834    /// single slice will result in a compile failure:
3835    ///
3836    /// ```compile_fail
3837    /// let mut slice = [1, 2, 3, 4, 5];
3838    ///
3839    /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3840    /// ```
3841    ///
3842    /// To work around this, we can use [`split_at_mut`] to create two distinct
3843    /// sub-slices from a slice:
3844    ///
3845    /// ```
3846    /// let mut slice = [1, 2, 3, 4, 5];
3847    ///
3848    /// {
3849    ///     let (left, right) = slice.split_at_mut(2);
3850    ///     left.clone_from_slice(&right[1..]);
3851    /// }
3852    ///
3853    /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3854    /// ```
3855    ///
3856    /// [`copy_from_slice`]: slice::copy_from_slice
3857    /// [`split_at_mut`]: slice::split_at_mut
3858    #[stable(feature = "clone_from_slice", since = "1.7.0")]
3859    #[track_caller]
3860    pub fn clone_from_slice(&mut self, src: &[T])
3861    where
3862        T: Clone,
3863    {
3864        self.spec_clone_from(src);
3865    }
3866
3867    /// Copies all elements from `src` into `self`, using a memcpy.
3868    ///
3869    /// The length of `src` must be the same as `self`.
3870    ///
3871    /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3872    ///
3873    /// # Panics
3874    ///
3875    /// This function will panic if the two slices have different lengths.
3876    ///
3877    /// # Examples
3878    ///
3879    /// Copying two elements from a slice into another:
3880    ///
3881    /// ```
3882    /// let src = [1, 2, 3, 4];
3883    /// let mut dst = [0, 0];
3884    ///
3885    /// // Because the slices have to be the same length,
3886    /// // we slice the source slice from four elements
3887    /// // to two. It will panic if we don't do this.
3888    /// dst.copy_from_slice(&src[2..]);
3889    ///
3890    /// assert_eq!(src, [1, 2, 3, 4]);
3891    /// assert_eq!(dst, [3, 4]);
3892    /// ```
3893    ///
3894    /// Rust enforces that there can only be one mutable reference with no
3895    /// immutable references to a particular piece of data in a particular
3896    /// scope. Because of this, attempting to use `copy_from_slice` on a
3897    /// single slice will result in a compile failure:
3898    ///
3899    /// ```compile_fail
3900    /// let mut slice = [1, 2, 3, 4, 5];
3901    ///
3902    /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3903    /// ```
3904    ///
3905    /// To work around this, we can use [`split_at_mut`] to create two distinct
3906    /// sub-slices from a slice:
3907    ///
3908    /// ```
3909    /// let mut slice = [1, 2, 3, 4, 5];
3910    ///
3911    /// {
3912    ///     let (left, right) = slice.split_at_mut(2);
3913    ///     left.copy_from_slice(&right[1..]);
3914    /// }
3915    ///
3916    /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3917    /// ```
3918    ///
3919    /// [`clone_from_slice`]: slice::clone_from_slice
3920    /// [`split_at_mut`]: slice::split_at_mut
3921    #[doc(alias = "memcpy")]
3922    #[inline]
3923    #[stable(feature = "copy_from_slice", since = "1.9.0")]
3924    #[rustc_const_stable(feature = "const_copy_from_slice", since = "1.87.0")]
3925    #[track_caller]
3926    pub const fn copy_from_slice(&mut self, src: &[T])
3927    where
3928        T: Copy,
3929    {
3930        // The panic code path was put into a cold function to not bloat the
3931        // call site.
3932        #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
3933        #[cfg_attr(feature = "panic_immediate_abort", inline)]
3934        #[track_caller]
3935        const fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3936            const_panic!(
3937                "copy_from_slice: source slice length does not match destination slice length",
3938                "copy_from_slice: source slice length ({src_len}) does not match destination slice length ({dst_len})",
3939                src_len: usize,
3940                dst_len: usize,
3941            )
3942        }
3943
3944        if self.len() != src.len() {
3945            len_mismatch_fail(self.len(), src.len());
3946        }
3947
3948        // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3949        // checked to have the same length. The slices cannot overlap because
3950        // mutable references are exclusive.
3951        unsafe {
3952            ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3953        }
3954    }
3955
3956    /// Copies elements from one part of the slice to another part of itself,
3957    /// using a memmove.
3958    ///
3959    /// `src` is the range within `self` to copy from. `dest` is the starting
3960    /// index of the range within `self` to copy to, which will have the same
3961    /// length as `src`. The two ranges may overlap. The ends of the two ranges
3962    /// must be less than or equal to `self.len()`.
3963    ///
3964    /// # Panics
3965    ///
3966    /// This function will panic if either range exceeds the end of the slice,
3967    /// or if the end of `src` is before the start.
3968    ///
3969    /// # Examples
3970    ///
3971    /// Copying four bytes within a slice:
3972    ///
3973    /// ```
3974    /// let mut bytes = *b"Hello, World!";
3975    ///
3976    /// bytes.copy_within(1..5, 8);
3977    ///
3978    /// assert_eq!(&bytes, b"Hello, Wello!");
3979    /// ```
3980    #[stable(feature = "copy_within", since = "1.37.0")]
3981    #[track_caller]
3982    pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3983    where
3984        T: Copy,
3985    {
3986        let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3987        let count = src_end - src_start;
3988        assert!(dest <= self.len() - count, "dest is out of bounds");
3989        // SAFETY: the conditions for `ptr::copy` have all been checked above,
3990        // as have those for `ptr::add`.
3991        unsafe {
3992            // Derive both `src_ptr` and `dest_ptr` from the same loan
3993            let ptr = self.as_mut_ptr();
3994            let src_ptr = ptr.add(src_start);
3995            let dest_ptr = ptr.add(dest);
3996            ptr::copy(src_ptr, dest_ptr, count);
3997        }
3998    }
3999
4000    /// Swaps all elements in `self` with those in `other`.
4001    ///
4002    /// The length of `other` must be the same as `self`.
4003    ///
4004    /// # Panics
4005    ///
4006    /// This function will panic if the two slices have different lengths.
4007    ///
4008    /// # Example
4009    ///
4010    /// Swapping two elements across slices:
4011    ///
4012    /// ```
4013    /// let mut slice1 = [0, 0];
4014    /// let mut slice2 = [1, 2, 3, 4];
4015    ///
4016    /// slice1.swap_with_slice(&mut slice2[2..]);
4017    ///
4018    /// assert_eq!(slice1, [3, 4]);
4019    /// assert_eq!(slice2, [1, 2, 0, 0]);
4020    /// ```
4021    ///
4022    /// Rust enforces that there can only be one mutable reference to a
4023    /// particular piece of data in a particular scope. Because of this,
4024    /// attempting to use `swap_with_slice` on a single slice will result in
4025    /// a compile failure:
4026    ///
4027    /// ```compile_fail
4028    /// let mut slice = [1, 2, 3, 4, 5];
4029    /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
4030    /// ```
4031    ///
4032    /// To work around this, we can use [`split_at_mut`] to create two distinct
4033    /// mutable sub-slices from a slice:
4034    ///
4035    /// ```
4036    /// let mut slice = [1, 2, 3, 4, 5];
4037    ///
4038    /// {
4039    ///     let (left, right) = slice.split_at_mut(2);
4040    ///     left.swap_with_slice(&mut right[1..]);
4041    /// }
4042    ///
4043    /// assert_eq!(slice, [4, 5, 3, 1, 2]);
4044    /// ```
4045    ///
4046    /// [`split_at_mut`]: slice::split_at_mut
4047    #[stable(feature = "swap_with_slice", since = "1.27.0")]
4048    #[track_caller]
4049    pub fn swap_with_slice(&mut self, other: &mut [T]) {
4050        assert!(self.len() == other.len(), "destination and source slices have different lengths");
4051        // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
4052        // checked to have the same length. The slices cannot overlap because
4053        // mutable references are exclusive.
4054        unsafe {
4055            ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
4056        }
4057    }
4058
4059    /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
4060    fn align_to_offsets<U>(&self) -> (usize, usize) {
4061        // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
4062        // lowest number of `T`s. And how many `T`s we need for each such "multiple".
4063        //
4064        // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
4065        // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
4066        // place of every 3 Ts in the `rest` slice. A bit more complicated.
4067        //
4068        // Formula to calculate this is:
4069        //
4070        // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
4071        // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
4072        //
4073        // Expanded and simplified:
4074        //
4075        // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
4076        // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
4077        //
4078        // Luckily since all this is constant-evaluated... performance here matters not!
4079        const fn gcd(a: usize, b: usize) -> usize {
4080            if b == 0 { a } else { gcd(b, a % b) }
4081        }
4082
4083        // Explicitly wrap the function call in a const block so it gets
4084        // constant-evaluated even in debug mode.
4085        let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
4086        let ts: usize = size_of::<U>() / gcd;
4087        let us: usize = size_of::<T>() / gcd;
4088
4089        // Armed with this knowledge, we can find how many `U`s we can fit!
4090        let us_len = self.len() / ts * us;
4091        // And how many `T`s will be in the trailing slice!
4092        let ts_len = self.len() % ts;
4093        (us_len, ts_len)
4094    }
4095
4096    /// Transmutes the slice to a slice of another type, ensuring alignment of the types is
4097    /// maintained.
4098    ///
4099    /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4100    /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4101    /// the given alignment constraint and element size.
4102    ///
4103    /// This method has no purpose when either input element `T` or output element `U` are
4104    /// zero-sized and will return the original slice without splitting anything.
4105    ///
4106    /// # Safety
4107    ///
4108    /// This method is essentially a `transmute` with respect to the elements in the returned
4109    /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4110    ///
4111    /// # Examples
4112    ///
4113    /// Basic usage:
4114    ///
4115    /// ```
4116    /// unsafe {
4117    ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4118    ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
4119    ///     // less_efficient_algorithm_for_bytes(prefix);
4120    ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
4121    ///     // less_efficient_algorithm_for_bytes(suffix);
4122    /// }
4123    /// ```
4124    #[stable(feature = "slice_align_to", since = "1.30.0")]
4125    #[must_use]
4126    pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
4127        // Note that most of this function will be constant-evaluated,
4128        if U::IS_ZST || T::IS_ZST {
4129            // handle ZSTs specially, which is – don't handle them at all.
4130            return (self, &[], &[]);
4131        }
4132
4133        // First, find at what point do we split between the first and 2nd slice. Easy with
4134        // ptr.align_offset.
4135        let ptr = self.as_ptr();
4136        // SAFETY: See the `align_to_mut` method for the detailed safety comment.
4137        let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4138        if offset > self.len() {
4139            (self, &[], &[])
4140        } else {
4141            let (left, rest) = self.split_at(offset);
4142            let (us_len, ts_len) = rest.align_to_offsets::<U>();
4143            // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4144            #[cfg(miri)]
4145            crate::intrinsics::miri_promise_symbolic_alignment(
4146                rest.as_ptr().cast(),
4147                align_of::<U>(),
4148            );
4149            // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
4150            // since the caller guarantees that we can transmute `T` to `U` safely.
4151            unsafe {
4152                (
4153                    left,
4154                    from_raw_parts(rest.as_ptr() as *const U, us_len),
4155                    from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
4156                )
4157            }
4158        }
4159    }
4160
4161    /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the
4162    /// types is maintained.
4163    ///
4164    /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4165    /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4166    /// the given alignment constraint and element size.
4167    ///
4168    /// This method has no purpose when either input element `T` or output element `U` are
4169    /// zero-sized and will return the original slice without splitting anything.
4170    ///
4171    /// # Safety
4172    ///
4173    /// This method is essentially a `transmute` with respect to the elements in the returned
4174    /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4175    ///
4176    /// # Examples
4177    ///
4178    /// Basic usage:
4179    ///
4180    /// ```
4181    /// unsafe {
4182    ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4183    ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
4184    ///     // less_efficient_algorithm_for_bytes(prefix);
4185    ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
4186    ///     // less_efficient_algorithm_for_bytes(suffix);
4187    /// }
4188    /// ```
4189    #[stable(feature = "slice_align_to", since = "1.30.0")]
4190    #[must_use]
4191    pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
4192        // Note that most of this function will be constant-evaluated,
4193        if U::IS_ZST || T::IS_ZST {
4194            // handle ZSTs specially, which is – don't handle them at all.
4195            return (self, &mut [], &mut []);
4196        }
4197
4198        // First, find at what point do we split between the first and 2nd slice. Easy with
4199        // ptr.align_offset.
4200        let ptr = self.as_ptr();
4201        // SAFETY: Here we are ensuring we will use aligned pointers for U for the
4202        // rest of the method. This is done by passing a pointer to &[T] with an
4203        // alignment targeted for U.
4204        // `crate::ptr::align_offset` is called with a correctly aligned and
4205        // valid pointer `ptr` (it comes from a reference to `self`) and with
4206        // a size that is a power of two (since it comes from the alignment for U),
4207        // satisfying its safety constraints.
4208        let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4209        if offset > self.len() {
4210            (self, &mut [], &mut [])
4211        } else {
4212            let (left, rest) = self.split_at_mut(offset);
4213            let (us_len, ts_len) = rest.align_to_offsets::<U>();
4214            let rest_len = rest.len();
4215            let mut_ptr = rest.as_mut_ptr();
4216            // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4217            #[cfg(miri)]
4218            crate::intrinsics::miri_promise_symbolic_alignment(
4219                mut_ptr.cast() as *const (),
4220                align_of::<U>(),
4221            );
4222            // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
4223            // SAFETY: see comments for `align_to`.
4224            unsafe {
4225                (
4226                    left,
4227                    from_raw_parts_mut(mut_ptr as *mut U, us_len),
4228                    from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
4229                )
4230            }
4231        }
4232    }
4233
4234    /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
4235    ///
4236    /// This is a safe wrapper around [`slice::align_to`], so inherits the same
4237    /// guarantees as that method.
4238    ///
4239    /// # Panics
4240    ///
4241    /// This will panic if the size of the SIMD type is different from
4242    /// `LANES` times that of the scalar.
4243    ///
4244    /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4245    /// that from ever happening, as only power-of-two numbers of lanes are
4246    /// supported.  It's possible that, in the future, those restrictions might
4247    /// be lifted in a way that would make it possible to see panics from this
4248    /// method for something like `LANES == 3`.
4249    ///
4250    /// # Examples
4251    ///
4252    /// ```
4253    /// #![feature(portable_simd)]
4254    /// use core::simd::prelude::*;
4255    ///
4256    /// let short = &[1, 2, 3];
4257    /// let (prefix, middle, suffix) = short.as_simd::<4>();
4258    /// assert_eq!(middle, []); // Not enough elements for anything in the middle
4259    ///
4260    /// // They might be split in any possible way between prefix and suffix
4261    /// let it = prefix.iter().chain(suffix).copied();
4262    /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
4263    ///
4264    /// fn basic_simd_sum(x: &[f32]) -> f32 {
4265    ///     use std::ops::Add;
4266    ///     let (prefix, middle, suffix) = x.as_simd();
4267    ///     let sums = f32x4::from_array([
4268    ///         prefix.iter().copied().sum(),
4269    ///         0.0,
4270    ///         0.0,
4271    ///         suffix.iter().copied().sum(),
4272    ///     ]);
4273    ///     let sums = middle.iter().copied().fold(sums, f32x4::add);
4274    ///     sums.reduce_sum()
4275    /// }
4276    ///
4277    /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
4278    /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
4279    /// ```
4280    #[unstable(feature = "portable_simd", issue = "86656")]
4281    #[must_use]
4282    pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
4283    where
4284        Simd<T, LANES>: AsRef<[T; LANES]>,
4285        T: simd::SimdElement,
4286        simd::LaneCount<LANES>: simd::SupportedLaneCount,
4287    {
4288        // These are expected to always match, as vector types are laid out like
4289        // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4290        // might as well double-check since it'll optimize away anyhow.
4291        assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4292
4293        // SAFETY: The simd types have the same layout as arrays, just with
4294        // potentially-higher alignment, so the de-facto transmutes are sound.
4295        unsafe { self.align_to() }
4296    }
4297
4298    /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,
4299    /// and a mutable suffix.
4300    ///
4301    /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4302    /// guarantees as that method.
4303    ///
4304    /// This is the mutable version of [`slice::as_simd`]; see that for examples.
4305    ///
4306    /// # Panics
4307    ///
4308    /// This will panic if the size of the SIMD type is different from
4309    /// `LANES` times that of the scalar.
4310    ///
4311    /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4312    /// that from ever happening, as only power-of-two numbers of lanes are
4313    /// supported.  It's possible that, in the future, those restrictions might
4314    /// be lifted in a way that would make it possible to see panics from this
4315    /// method for something like `LANES == 3`.
4316    #[unstable(feature = "portable_simd", issue = "86656")]
4317    #[must_use]
4318    pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
4319    where
4320        Simd<T, LANES>: AsMut<[T; LANES]>,
4321        T: simd::SimdElement,
4322        simd::LaneCount<LANES>: simd::SupportedLaneCount,
4323    {
4324        // These are expected to always match, as vector types are laid out like
4325        // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4326        // might as well double-check since it'll optimize away anyhow.
4327        assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4328
4329        // SAFETY: The simd types have the same layout as arrays, just with
4330        // potentially-higher alignment, so the de-facto transmutes are sound.
4331        unsafe { self.align_to_mut() }
4332    }
4333
4334    /// Checks if the elements of this slice are sorted.
4335    ///
4336    /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4337    /// slice yields exactly zero or one element, `true` is returned.
4338    ///
4339    /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4340    /// implies that this function returns `false` if any two consecutive items are not
4341    /// comparable.
4342    ///
4343    /// # Examples
4344    ///
4345    /// ```
4346    /// let empty: [i32; 0] = [];
4347    ///
4348    /// assert!([1, 2, 2, 9].is_sorted());
4349    /// assert!(![1, 3, 2, 4].is_sorted());
4350    /// assert!([0].is_sorted());
4351    /// assert!(empty.is_sorted());
4352    /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
4353    /// ```
4354    #[inline]
4355    #[stable(feature = "is_sorted", since = "1.82.0")]
4356    #[must_use]
4357    pub fn is_sorted(&self) -> bool
4358    where
4359        T: PartialOrd,
4360    {
4361        // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.
4362        const CHUNK_SIZE: usize = 33;
4363        if self.len() < CHUNK_SIZE {
4364            return self.windows(2).all(|w| w[0] <= w[1]);
4365        }
4366        let mut i = 0;
4367        // Check in chunks for autovectorization.
4368        while i < self.len() - CHUNK_SIZE {
4369            let chunk = &self[i..i + CHUNK_SIZE];
4370            if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {
4371                return false;
4372            }
4373            // We need to ensure that chunk boundaries are also sorted.
4374            // Overlap the next chunk with the last element of our last chunk.
4375            i += CHUNK_SIZE - 1;
4376        }
4377        self[i..].windows(2).all(|w| w[0] <= w[1])
4378    }
4379
4380    /// Checks if the elements of this slice are sorted using the given comparator function.
4381    ///
4382    /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4383    /// function to determine whether two elements are to be considered in sorted order.
4384    ///
4385    /// # Examples
4386    ///
4387    /// ```
4388    /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
4389    /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
4390    ///
4391    /// assert!([0].is_sorted_by(|a, b| true));
4392    /// assert!([0].is_sorted_by(|a, b| false));
4393    ///
4394    /// let empty: [i32; 0] = [];
4395    /// assert!(empty.is_sorted_by(|a, b| false));
4396    /// assert!(empty.is_sorted_by(|a, b| true));
4397    /// ```
4398    #[stable(feature = "is_sorted", since = "1.82.0")]
4399    #[must_use]
4400    pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
4401    where
4402        F: FnMut(&'a T, &'a T) -> bool,
4403    {
4404        self.array_windows().all(|[a, b]| compare(a, b))
4405    }
4406
4407    /// Checks if the elements of this slice are sorted using the given key extraction function.
4408    ///
4409    /// Instead of comparing the slice's elements directly, this function compares the keys of the
4410    /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
4411    /// documentation for more information.
4412    ///
4413    /// [`is_sorted`]: slice::is_sorted
4414    ///
4415    /// # Examples
4416    ///
4417    /// ```
4418    /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
4419    /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
4420    /// ```
4421    #[inline]
4422    #[stable(feature = "is_sorted", since = "1.82.0")]
4423    #[must_use]
4424    pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
4425    where
4426        F: FnMut(&'a T) -> K,
4427        K: PartialOrd,
4428    {
4429        self.iter().is_sorted_by_key(f)
4430    }
4431
4432    /// Returns the index of the partition point according to the given predicate
4433    /// (the index of the first element of the second partition).
4434    ///
4435    /// The slice is assumed to be partitioned according to the given predicate.
4436    /// This means that all elements for which the predicate returns true are at the start of the slice
4437    /// and all elements for which the predicate returns false are at the end.
4438    /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
4439    /// (all odd numbers are at the start, all even at the end).
4440    ///
4441    /// If this slice is not partitioned, the returned result is unspecified and meaningless,
4442    /// as this method performs a kind of binary search.
4443    ///
4444    /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
4445    ///
4446    /// [`binary_search`]: slice::binary_search
4447    /// [`binary_search_by`]: slice::binary_search_by
4448    /// [`binary_search_by_key`]: slice::binary_search_by_key
4449    ///
4450    /// # Examples
4451    ///
4452    /// ```
4453    /// let v = [1, 2, 3, 3, 5, 6, 7];
4454    /// let i = v.partition_point(|&x| x < 5);
4455    ///
4456    /// assert_eq!(i, 4);
4457    /// assert!(v[..i].iter().all(|&x| x < 5));
4458    /// assert!(v[i..].iter().all(|&x| !(x < 5)));
4459    /// ```
4460    ///
4461    /// If all elements of the slice match the predicate, including if the slice
4462    /// is empty, then the length of the slice will be returned:
4463    ///
4464    /// ```
4465    /// let a = [2, 4, 8];
4466    /// assert_eq!(a.partition_point(|x| x < &100), a.len());
4467    /// let a: [i32; 0] = [];
4468    /// assert_eq!(a.partition_point(|x| x < &100), 0);
4469    /// ```
4470    ///
4471    /// If you want to insert an item to a sorted vector, while maintaining
4472    /// sort order:
4473    ///
4474    /// ```
4475    /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
4476    /// let num = 42;
4477    /// let idx = s.partition_point(|&x| x <= num);
4478    /// s.insert(idx, num);
4479    /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
4480    /// ```
4481    #[stable(feature = "partition_point", since = "1.52.0")]
4482    #[must_use]
4483    pub fn partition_point<P>(&self, mut pred: P) -> usize
4484    where
4485        P: FnMut(&T) -> bool,
4486    {
4487        self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
4488    }
4489
4490    /// Removes the subslice corresponding to the given range
4491    /// and returns a reference to it.
4492    ///
4493    /// Returns `None` and does not modify the slice if the given
4494    /// range is out of bounds.
4495    ///
4496    /// Note that this method only accepts one-sided ranges such as
4497    /// `2..` or `..6`, but not `2..6`.
4498    ///
4499    /// # Examples
4500    ///
4501    /// Splitting off the first three elements of a slice:
4502    ///
4503    /// ```
4504    /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4505    /// let mut first_three = slice.split_off(..3).unwrap();
4506    ///
4507    /// assert_eq!(slice, &['d']);
4508    /// assert_eq!(first_three, &['a', 'b', 'c']);
4509    /// ```
4510    ///
4511    /// Splitting off a slice starting with the third element:
4512    ///
4513    /// ```
4514    /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4515    /// let mut tail = slice.split_off(2..).unwrap();
4516    ///
4517    /// assert_eq!(slice, &['a', 'b']);
4518    /// assert_eq!(tail, &['c', 'd']);
4519    /// ```
4520    ///
4521    /// Getting `None` when `range` is out of bounds:
4522    ///
4523    /// ```
4524    /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4525    ///
4526    /// assert_eq!(None, slice.split_off(5..));
4527    /// assert_eq!(None, slice.split_off(..5));
4528    /// assert_eq!(None, slice.split_off(..=4));
4529    /// let expected: &[char] = &['a', 'b', 'c', 'd'];
4530    /// assert_eq!(Some(expected), slice.split_off(..4));
4531    /// ```
4532    #[inline]
4533    #[must_use = "method does not modify the slice if the range is out of bounds"]
4534    #[stable(feature = "slice_take", since = "1.87.0")]
4535    pub fn split_off<'a, R: OneSidedRange<usize>>(
4536        self: &mut &'a Self,
4537        range: R,
4538    ) -> Option<&'a Self> {
4539        let (direction, split_index) = split_point_of(range)?;
4540        if split_index > self.len() {
4541            return None;
4542        }
4543        let (front, back) = self.split_at(split_index);
4544        match direction {
4545            Direction::Front => {
4546                *self = back;
4547                Some(front)
4548            }
4549            Direction::Back => {
4550                *self = front;
4551                Some(back)
4552            }
4553        }
4554    }
4555
4556    /// Removes the subslice corresponding to the given range
4557    /// and returns a mutable reference to it.
4558    ///
4559    /// Returns `None` and does not modify the slice if the given
4560    /// range is out of bounds.
4561    ///
4562    /// Note that this method only accepts one-sided ranges such as
4563    /// `2..` or `..6`, but not `2..6`.
4564    ///
4565    /// # Examples
4566    ///
4567    /// Splitting off the first three elements of a slice:
4568    ///
4569    /// ```
4570    /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4571    /// let mut first_three = slice.split_off_mut(..3).unwrap();
4572    ///
4573    /// assert_eq!(slice, &mut ['d']);
4574    /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
4575    /// ```
4576    ///
4577    /// Splitting off a slice starting with the third element:
4578    ///
4579    /// ```
4580    /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4581    /// let mut tail = slice.split_off_mut(2..).unwrap();
4582    ///
4583    /// assert_eq!(slice, &mut ['a', 'b']);
4584    /// assert_eq!(tail, &mut ['c', 'd']);
4585    /// ```
4586    ///
4587    /// Getting `None` when `range` is out of bounds:
4588    ///
4589    /// ```
4590    /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4591    ///
4592    /// assert_eq!(None, slice.split_off_mut(5..));
4593    /// assert_eq!(None, slice.split_off_mut(..5));
4594    /// assert_eq!(None, slice.split_off_mut(..=4));
4595    /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4596    /// assert_eq!(Some(expected), slice.split_off_mut(..4));
4597    /// ```
4598    #[inline]
4599    #[must_use = "method does not modify the slice if the range is out of bounds"]
4600    #[stable(feature = "slice_take", since = "1.87.0")]
4601    pub fn split_off_mut<'a, R: OneSidedRange<usize>>(
4602        self: &mut &'a mut Self,
4603        range: R,
4604    ) -> Option<&'a mut Self> {
4605        let (direction, split_index) = split_point_of(range)?;
4606        if split_index > self.len() {
4607            return None;
4608        }
4609        let (front, back) = mem::take(self).split_at_mut(split_index);
4610        match direction {
4611            Direction::Front => {
4612                *self = back;
4613                Some(front)
4614            }
4615            Direction::Back => {
4616                *self = front;
4617                Some(back)
4618            }
4619        }
4620    }
4621
4622    /// Removes the first element of the slice and returns a reference
4623    /// to it.
4624    ///
4625    /// Returns `None` if the slice is empty.
4626    ///
4627    /// # Examples
4628    ///
4629    /// ```
4630    /// let mut slice: &[_] = &['a', 'b', 'c'];
4631    /// let first = slice.split_off_first().unwrap();
4632    ///
4633    /// assert_eq!(slice, &['b', 'c']);
4634    /// assert_eq!(first, &'a');
4635    /// ```
4636    #[inline]
4637    #[stable(feature = "slice_take", since = "1.87.0")]
4638    #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4639    pub const fn split_off_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4640        // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4641        let Some((first, rem)) = self.split_first() else { return None };
4642        *self = rem;
4643        Some(first)
4644    }
4645
4646    /// Removes the first element of the slice and returns a mutable
4647    /// reference to it.
4648    ///
4649    /// Returns `None` if the slice is empty.
4650    ///
4651    /// # Examples
4652    ///
4653    /// ```
4654    /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4655    /// let first = slice.split_off_first_mut().unwrap();
4656    /// *first = 'd';
4657    ///
4658    /// assert_eq!(slice, &['b', 'c']);
4659    /// assert_eq!(first, &'d');
4660    /// ```
4661    #[inline]
4662    #[stable(feature = "slice_take", since = "1.87.0")]
4663    #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4664    pub const fn split_off_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4665        // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4666        // Original: `mem::take(self).split_first_mut()?`
4667        let Some((first, rem)) = mem::replace(self, &mut []).split_first_mut() else { return None };
4668        *self = rem;
4669        Some(first)
4670    }
4671
4672    /// Removes the last element of the slice and returns a reference
4673    /// to it.
4674    ///
4675    /// Returns `None` if the slice is empty.
4676    ///
4677    /// # Examples
4678    ///
4679    /// ```
4680    /// let mut slice: &[_] = &['a', 'b', 'c'];
4681    /// let last = slice.split_off_last().unwrap();
4682    ///
4683    /// assert_eq!(slice, &['a', 'b']);
4684    /// assert_eq!(last, &'c');
4685    /// ```
4686    #[inline]
4687    #[stable(feature = "slice_take", since = "1.87.0")]
4688    #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4689    pub const fn split_off_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4690        // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4691        let Some((last, rem)) = self.split_last() else { return None };
4692        *self = rem;
4693        Some(last)
4694    }
4695
4696    /// Removes the last element of the slice and returns a mutable
4697    /// reference to it.
4698    ///
4699    /// Returns `None` if the slice is empty.
4700    ///
4701    /// # Examples
4702    ///
4703    /// ```
4704    /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4705    /// let last = slice.split_off_last_mut().unwrap();
4706    /// *last = 'd';
4707    ///
4708    /// assert_eq!(slice, &['a', 'b']);
4709    /// assert_eq!(last, &'d');
4710    /// ```
4711    #[inline]
4712    #[stable(feature = "slice_take", since = "1.87.0")]
4713    #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4714    pub const fn split_off_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4715        // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4716        // Original: `mem::take(self).split_last_mut()?`
4717        let Some((last, rem)) = mem::replace(self, &mut []).split_last_mut() else { return None };
4718        *self = rem;
4719        Some(last)
4720    }
4721
4722    /// Returns mutable references to many indices at once, without doing any checks.
4723    ///
4724    /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4725    /// that this method takes an array, so all indices must be of the same type.
4726    /// If passed an array of `usize`s this method gives back an array of mutable references
4727    /// to single elements, while if passed an array of ranges it gives back an array of
4728    /// mutable references to slices.
4729    ///
4730    /// For a safe alternative see [`get_disjoint_mut`].
4731    ///
4732    /// # Safety
4733    ///
4734    /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4735    /// even if the resulting references are not used.
4736    ///
4737    /// # Examples
4738    ///
4739    /// ```
4740    /// let x = &mut [1, 2, 4];
4741    ///
4742    /// unsafe {
4743    ///     let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
4744    ///     *a *= 10;
4745    ///     *b *= 100;
4746    /// }
4747    /// assert_eq!(x, &[10, 2, 400]);
4748    ///
4749    /// unsafe {
4750    ///     let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
4751    ///     a[0] = 8;
4752    ///     b[0] = 88;
4753    ///     b[1] = 888;
4754    /// }
4755    /// assert_eq!(x, &[8, 88, 888]);
4756    ///
4757    /// unsafe {
4758    ///     let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
4759    ///     a[0] = 11;
4760    ///     a[1] = 111;
4761    ///     b[0] = 1;
4762    /// }
4763    /// assert_eq!(x, &[1, 11, 111]);
4764    /// ```
4765    ///
4766    /// [`get_disjoint_mut`]: slice::get_disjoint_mut
4767    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4768    #[stable(feature = "get_many_mut", since = "1.86.0")]
4769    #[inline]
4770    #[track_caller]
4771    pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
4772        &mut self,
4773        indices: [I; N],
4774    ) -> [&mut I::Output; N]
4775    where
4776        I: GetDisjointMutIndex + SliceIndex<Self>,
4777    {
4778        // NB: This implementation is written as it is because any variation of
4779        // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4780        // or generate worse code otherwise. This is also why we need to go
4781        // through a raw pointer here.
4782        let slice: *mut [T] = self;
4783        let mut arr: MaybeUninit<[&mut I::Output; N]> = MaybeUninit::uninit();
4784        let arr_ptr = arr.as_mut_ptr();
4785
4786        // SAFETY: We expect `indices` to contain disjunct values that are
4787        // in bounds of `self`.
4788        unsafe {
4789            for i in 0..N {
4790                let idx = indices.get_unchecked(i).clone();
4791                arr_ptr.cast::<&mut I::Output>().add(i).write(&mut *slice.get_unchecked_mut(idx));
4792            }
4793            arr.assume_init()
4794        }
4795    }
4796
4797    /// Returns mutable references to many indices at once.
4798    ///
4799    /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4800    /// that this method takes an array, so all indices must be of the same type.
4801    /// If passed an array of `usize`s this method gives back an array of mutable references
4802    /// to single elements, while if passed an array of ranges it gives back an array of
4803    /// mutable references to slices.
4804    ///
4805    /// Returns an error if any index is out-of-bounds, or if there are overlapping indices.
4806    /// An empty range is not considered to overlap if it is located at the beginning or at
4807    /// the end of another range, but is considered to overlap if it is located in the middle.
4808    ///
4809    /// This method does a O(n^2) check to check that there are no overlapping indices, so be careful
4810    /// when passing many indices.
4811    ///
4812    /// # Examples
4813    ///
4814    /// ```
4815    /// let v = &mut [1, 2, 3];
4816    /// if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
4817    ///     *a = 413;
4818    ///     *b = 612;
4819    /// }
4820    /// assert_eq!(v, &[413, 2, 612]);
4821    ///
4822    /// if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
4823    ///     a[0] = 8;
4824    ///     b[0] = 88;
4825    ///     b[1] = 888;
4826    /// }
4827    /// assert_eq!(v, &[8, 88, 888]);
4828    ///
4829    /// if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
4830    ///     a[0] = 11;
4831    ///     a[1] = 111;
4832    ///     b[0] = 1;
4833    /// }
4834    /// assert_eq!(v, &[1, 11, 111]);
4835    /// ```
4836    #[stable(feature = "get_many_mut", since = "1.86.0")]
4837    #[inline]
4838    pub fn get_disjoint_mut<I, const N: usize>(
4839        &mut self,
4840        indices: [I; N],
4841    ) -> Result<[&mut I::Output; N], GetDisjointMutError>
4842    where
4843        I: GetDisjointMutIndex + SliceIndex<Self>,
4844    {
4845        get_disjoint_check_valid(&indices, self.len())?;
4846        // SAFETY: The `get_disjoint_check_valid()` call checked that all indices
4847        // are disjunct and in bounds.
4848        unsafe { Ok(self.get_disjoint_unchecked_mut(indices)) }
4849    }
4850
4851    /// Returns the index that an element reference points to.
4852    ///
4853    /// Returns `None` if `element` does not point to the start of an element within the slice.
4854    ///
4855    /// This method is useful for extending slice iterators like [`slice::split`].
4856    ///
4857    /// Note that this uses pointer arithmetic and **does not compare elements**.
4858    /// To find the index of an element via comparison, use
4859    /// [`.iter().position()`](crate::iter::Iterator::position) instead.
4860    ///
4861    /// # Panics
4862    /// Panics if `T` is zero-sized.
4863    ///
4864    /// # Examples
4865    /// Basic usage:
4866    /// ```
4867    /// #![feature(substr_range)]
4868    ///
4869    /// let nums: &[u32] = &[1, 7, 1, 1];
4870    /// let num = &nums[2];
4871    ///
4872    /// assert_eq!(num, &1);
4873    /// assert_eq!(nums.element_offset(num), Some(2));
4874    /// ```
4875    /// Returning `None` with an unaligned element:
4876    /// ```
4877    /// #![feature(substr_range)]
4878    ///
4879    /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
4880    /// let flat_arr: &[u32] = arr.as_flattened();
4881    ///
4882    /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
4883    /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
4884    ///
4885    /// assert_eq!(ok_elm, &[0, 1]);
4886    /// assert_eq!(weird_elm, &[1, 2]);
4887    ///
4888    /// assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
4889    /// assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
4890    /// ```
4891    #[must_use]
4892    #[unstable(feature = "substr_range", issue = "126769")]
4893    pub fn element_offset(&self, element: &T) -> Option<usize> {
4894        if T::IS_ZST {
4895            panic!("elements are zero-sized");
4896        }
4897
4898        let self_start = self.as_ptr().addr();
4899        let elem_start = ptr::from_ref(element).addr();
4900
4901        let byte_offset = elem_start.wrapping_sub(self_start);
4902
4903        if !byte_offset.is_multiple_of(size_of::<T>()) {
4904            return None;
4905        }
4906
4907        let offset = byte_offset / size_of::<T>();
4908
4909        if offset < self.len() { Some(offset) } else { None }
4910    }
4911
4912    /// Returns the range of indices that a subslice points to.
4913    ///
4914    /// Returns `None` if `subslice` does not point within the slice or if it is not aligned with the
4915    /// elements in the slice.
4916    ///
4917    /// This method **does not compare elements**. Instead, this method finds the location in the slice that
4918    /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use
4919    /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position).
4920    ///
4921    /// This method is useful for extending slice iterators like [`slice::split`].
4922    ///
4923    /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`)
4924    /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice.
4925    ///
4926    /// # Panics
4927    /// Panics if `T` is zero-sized.
4928    ///
4929    /// # Examples
4930    /// Basic usage:
4931    /// ```
4932    /// #![feature(substr_range)]
4933    ///
4934    /// let nums = &[0, 5, 10, 0, 0, 5];
4935    ///
4936    /// let mut iter = nums
4937    ///     .split(|t| *t == 0)
4938    ///     .map(|n| nums.subslice_range(n).unwrap());
4939    ///
4940    /// assert_eq!(iter.next(), Some(0..0));
4941    /// assert_eq!(iter.next(), Some(1..3));
4942    /// assert_eq!(iter.next(), Some(4..4));
4943    /// assert_eq!(iter.next(), Some(5..6));
4944    /// ```
4945    #[must_use]
4946    #[unstable(feature = "substr_range", issue = "126769")]
4947    pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>> {
4948        if T::IS_ZST {
4949            panic!("elements are zero-sized");
4950        }
4951
4952        let self_start = self.as_ptr().addr();
4953        let subslice_start = subslice.as_ptr().addr();
4954
4955        let byte_start = subslice_start.wrapping_sub(self_start);
4956
4957        if !byte_start.is_multiple_of(size_of::<T>()) {
4958            return None;
4959        }
4960
4961        let start = byte_start / size_of::<T>();
4962        let end = start.wrapping_add(subslice.len());
4963
4964        if start <= self.len() && end <= self.len() { Some(start..end) } else { None }
4965    }
4966}
4967
4968impl<T> [MaybeUninit<T>] {
4969    /// Transmutes the mutable uninitialized slice to a mutable uninitialized slice of
4970    /// another type, ensuring alignment of the types is maintained.
4971    ///
4972    /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4973    /// guarantees as that method.
4974    ///
4975    /// # Examples
4976    ///
4977    /// ```
4978    /// #![feature(align_to_uninit_mut)]
4979    /// use std::mem::MaybeUninit;
4980    ///
4981    /// pub struct BumpAllocator<'scope> {
4982    ///     memory: &'scope mut [MaybeUninit<u8>],
4983    /// }
4984    ///
4985    /// impl<'scope> BumpAllocator<'scope> {
4986    ///     pub fn new(memory: &'scope mut [MaybeUninit<u8>]) -> Self {
4987    ///         Self { memory }
4988    ///     }
4989    ///     pub fn try_alloc_uninit<T>(&mut self) -> Option<&'scope mut MaybeUninit<T>> {
4990    ///         let first_end = self.memory.as_ptr().align_offset(align_of::<T>()) + size_of::<T>();
4991    ///         let prefix = self.memory.split_off_mut(..first_end)?;
4992    ///         Some(&mut prefix.align_to_uninit_mut::<T>().1[0])
4993    ///     }
4994    ///     pub fn try_alloc_u32(&mut self, value: u32) -> Option<&'scope mut u32> {
4995    ///         let uninit = self.try_alloc_uninit()?;
4996    ///         Some(uninit.write(value))
4997    ///     }
4998    /// }
4999    ///
5000    /// let mut memory = [MaybeUninit::<u8>::uninit(); 10];
5001    /// let mut allocator = BumpAllocator::new(&mut memory);
5002    /// let v = allocator.try_alloc_u32(42);
5003    /// assert_eq!(v, Some(&mut 42));
5004    /// ```
5005    #[unstable(feature = "align_to_uninit_mut", issue = "139062")]
5006    #[inline]
5007    #[must_use]
5008    pub fn align_to_uninit_mut<U>(&mut self) -> (&mut Self, &mut [MaybeUninit<U>], &mut Self) {
5009        // SAFETY: `MaybeUninit` is transparent. Correct size and alignment are guaranteed by
5010        // `align_to_mut` itself. Therefore the only thing that we have to ensure for a safe
5011        // `transmute` is that the values are valid for the types involved. But for `MaybeUninit`
5012        // any values are valid, so this operation is safe.
5013        unsafe { self.align_to_mut() }
5014    }
5015}
5016
5017impl<T, const N: usize> [[T; N]] {
5018    /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
5019    ///
5020    /// For the opposite operation, see [`as_chunks`] and [`as_rchunks`].
5021    ///
5022    /// [`as_chunks`]: slice::as_chunks
5023    /// [`as_rchunks`]: slice::as_rchunks
5024    ///
5025    /// # Panics
5026    ///
5027    /// This panics if the length of the resulting slice would overflow a `usize`.
5028    ///
5029    /// This is only possible when flattening a slice of arrays of zero-sized
5030    /// types, and thus tends to be irrelevant in practice. If
5031    /// `size_of::<T>() > 0`, this will never panic.
5032    ///
5033    /// # Examples
5034    ///
5035    /// ```
5036    /// assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
5037    ///
5038    /// assert_eq!(
5039    ///     [[1, 2, 3], [4, 5, 6]].as_flattened(),
5040    ///     [[1, 2], [3, 4], [5, 6]].as_flattened(),
5041    /// );
5042    ///
5043    /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
5044    /// assert!(slice_of_empty_arrays.as_flattened().is_empty());
5045    ///
5046    /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
5047    /// assert!(empty_slice_of_arrays.as_flattened().is_empty());
5048    /// ```
5049    #[stable(feature = "slice_flatten", since = "1.80.0")]
5050    #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5051    pub const fn as_flattened(&self) -> &[T] {
5052        let len = if T::IS_ZST {
5053            self.len().checked_mul(N).expect("slice len overflow")
5054        } else {
5055            // SAFETY: `self.len() * N` cannot overflow because `self` is
5056            // already in the address space.
5057            unsafe { self.len().unchecked_mul(N) }
5058        };
5059        // SAFETY: `[T]` is layout-identical to `[T; N]`
5060        unsafe { from_raw_parts(self.as_ptr().cast(), len) }
5061    }
5062
5063    /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
5064    ///
5065    /// For the opposite operation, see [`as_chunks_mut`] and [`as_rchunks_mut`].
5066    ///
5067    /// [`as_chunks_mut`]: slice::as_chunks_mut
5068    /// [`as_rchunks_mut`]: slice::as_rchunks_mut
5069    ///
5070    /// # Panics
5071    ///
5072    /// This panics if the length of the resulting slice would overflow a `usize`.
5073    ///
5074    /// This is only possible when flattening a slice of arrays of zero-sized
5075    /// types, and thus tends to be irrelevant in practice. If
5076    /// `size_of::<T>() > 0`, this will never panic.
5077    ///
5078    /// # Examples
5079    ///
5080    /// ```
5081    /// fn add_5_to_all(slice: &mut [i32]) {
5082    ///     for i in slice {
5083    ///         *i += 5;
5084    ///     }
5085    /// }
5086    ///
5087    /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
5088    /// add_5_to_all(array.as_flattened_mut());
5089    /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
5090    /// ```
5091    #[stable(feature = "slice_flatten", since = "1.80.0")]
5092    #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5093    pub const fn as_flattened_mut(&mut self) -> &mut [T] {
5094        let len = if T::IS_ZST {
5095            self.len().checked_mul(N).expect("slice len overflow")
5096        } else {
5097            // SAFETY: `self.len() * N` cannot overflow because `self` is
5098            // already in the address space.
5099            unsafe { self.len().unchecked_mul(N) }
5100        };
5101        // SAFETY: `[T]` is layout-identical to `[T; N]`
5102        unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
5103    }
5104}
5105
5106impl [f32] {
5107    /// Sorts the slice of floats.
5108    ///
5109    /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5110    /// the ordering defined by [`f32::total_cmp`].
5111    ///
5112    /// # Current implementation
5113    ///
5114    /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5115    ///
5116    /// # Examples
5117    ///
5118    /// ```
5119    /// #![feature(sort_floats)]
5120    /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
5121    ///
5122    /// v.sort_floats();
5123    /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
5124    /// assert_eq!(&v[..8], &sorted[..8]);
5125    /// assert!(v[8].is_nan());
5126    /// ```
5127    #[unstable(feature = "sort_floats", issue = "93396")]
5128    #[inline]
5129    pub fn sort_floats(&mut self) {
5130        self.sort_unstable_by(f32::total_cmp);
5131    }
5132}
5133
5134impl [f64] {
5135    /// Sorts the slice of floats.
5136    ///
5137    /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5138    /// the ordering defined by [`f64::total_cmp`].
5139    ///
5140    /// # Current implementation
5141    ///
5142    /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5143    ///
5144    /// # Examples
5145    ///
5146    /// ```
5147    /// #![feature(sort_floats)]
5148    /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
5149    ///
5150    /// v.sort_floats();
5151    /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
5152    /// assert_eq!(&v[..8], &sorted[..8]);
5153    /// assert!(v[8].is_nan());
5154    /// ```
5155    #[unstable(feature = "sort_floats", issue = "93396")]
5156    #[inline]
5157    pub fn sort_floats(&mut self) {
5158        self.sort_unstable_by(f64::total_cmp);
5159    }
5160}
5161
5162trait CloneFromSpec<T> {
5163    fn spec_clone_from(&mut self, src: &[T]);
5164}
5165
5166impl<T> CloneFromSpec<T> for [T]
5167where
5168    T: Clone,
5169{
5170    #[track_caller]
5171    default fn spec_clone_from(&mut self, src: &[T]) {
5172        assert!(self.len() == src.len(), "destination and source slices have different lengths");
5173        // NOTE: We need to explicitly slice them to the same length
5174        // to make it easier for the optimizer to elide bounds checking.
5175        // But since it can't be relied on we also have an explicit specialization for T: Copy.
5176        let len = self.len();
5177        let src = &src[..len];
5178        for i in 0..len {
5179            self[i].clone_from(&src[i]);
5180        }
5181    }
5182}
5183
5184impl<T> CloneFromSpec<T> for [T]
5185where
5186    T: Copy,
5187{
5188    #[track_caller]
5189    fn spec_clone_from(&mut self, src: &[T]) {
5190        self.copy_from_slice(src);
5191    }
5192}
5193
5194#[stable(feature = "rust1", since = "1.0.0")]
5195#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5196impl<T> const Default for &[T] {
5197    /// Creates an empty slice.
5198    fn default() -> Self {
5199        &[]
5200    }
5201}
5202
5203#[stable(feature = "mut_slice_default", since = "1.5.0")]
5204#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5205impl<T> const Default for &mut [T] {
5206    /// Creates a mutable empty slice.
5207    fn default() -> Self {
5208        &mut []
5209    }
5210}
5211
5212#[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
5213/// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`.  At a future
5214/// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
5215/// `str`) to slices, and then this trait will be replaced or abolished.
5216pub trait SlicePattern {
5217    /// The element type of the slice being matched on.
5218    type Item;
5219
5220    /// Currently, the consumers of `SlicePattern` need a slice.
5221    fn as_slice(&self) -> &[Self::Item];
5222}
5223
5224#[stable(feature = "slice_strip", since = "1.51.0")]
5225impl<T> SlicePattern for [T] {
5226    type Item = T;
5227
5228    #[inline]
5229    fn as_slice(&self) -> &[Self::Item] {
5230        self
5231    }
5232}
5233
5234#[stable(feature = "slice_strip", since = "1.51.0")]
5235impl<T, const N: usize> SlicePattern for [T; N] {
5236    type Item = T;
5237
5238    #[inline]
5239    fn as_slice(&self) -> &[Self::Item] {
5240        self
5241    }
5242}
5243
5244/// This checks every index against each other, and against `len`.
5245///
5246/// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
5247/// comparison operations.
5248#[inline]
5249fn get_disjoint_check_valid<I: GetDisjointMutIndex, const N: usize>(
5250    indices: &[I; N],
5251    len: usize,
5252) -> Result<(), GetDisjointMutError> {
5253    // NB: The optimizer should inline the loops into a sequence
5254    // of instructions without additional branching.
5255    for (i, idx) in indices.iter().enumerate() {
5256        if !idx.is_in_bounds(len) {
5257            return Err(GetDisjointMutError::IndexOutOfBounds);
5258        }
5259        for idx2 in &indices[..i] {
5260            if idx.is_overlapping(idx2) {
5261                return Err(GetDisjointMutError::OverlappingIndices);
5262            }
5263        }
5264    }
5265    Ok(())
5266}
5267
5268/// The error type returned by [`get_disjoint_mut`][`slice::get_disjoint_mut`].
5269///
5270/// It indicates one of two possible errors:
5271/// - An index is out-of-bounds.
5272/// - The same index appeared multiple times in the array
5273///   (or different but overlapping indices when ranges are provided).
5274///
5275/// # Examples
5276///
5277/// ```
5278/// use std::slice::GetDisjointMutError;
5279///
5280/// let v = &mut [1, 2, 3];
5281/// assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds));
5282/// assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices));
5283/// ```
5284#[stable(feature = "get_many_mut", since = "1.86.0")]
5285#[derive(Debug, Clone, PartialEq, Eq)]
5286pub enum GetDisjointMutError {
5287    /// An index provided was out-of-bounds for the slice.
5288    IndexOutOfBounds,
5289    /// Two indices provided were overlapping.
5290    OverlappingIndices,
5291}
5292
5293#[stable(feature = "get_many_mut", since = "1.86.0")]
5294impl fmt::Display for GetDisjointMutError {
5295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5296        let msg = match self {
5297            GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",
5298            GetDisjointMutError::OverlappingIndices => "there were overlapping indices",
5299        };
5300        fmt::Display::fmt(msg, f)
5301    }
5302}
5303
5304mod private_get_disjoint_mut_index {
5305    use super::{Range, RangeInclusive, range};
5306
5307    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5308    pub trait Sealed {}
5309
5310    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5311    impl Sealed for usize {}
5312    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5313    impl Sealed for Range<usize> {}
5314    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5315    impl Sealed for RangeInclusive<usize> {}
5316    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5317    impl Sealed for range::Range<usize> {}
5318    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5319    impl Sealed for range::RangeInclusive<usize> {}
5320}
5321
5322/// A helper trait for `<[T]>::get_disjoint_mut()`.
5323///
5324/// # Safety
5325///
5326/// If `is_in_bounds()` returns `true` and `is_overlapping()` returns `false`,
5327/// it must be safe to index the slice with the indices.
5328#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5329pub unsafe trait GetDisjointMutIndex:
5330    Clone + private_get_disjoint_mut_index::Sealed
5331{
5332    /// Returns `true` if `self` is in bounds for `len` slice elements.
5333    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5334    fn is_in_bounds(&self, len: usize) -> bool;
5335
5336    /// Returns `true` if `self` overlaps with `other`.
5337    ///
5338    /// Note that we don't consider zero-length ranges to overlap at the beginning or the end,
5339    /// but do consider them to overlap in the middle.
5340    #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5341    fn is_overlapping(&self, other: &Self) -> bool;
5342}
5343
5344#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5345// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5346unsafe impl GetDisjointMutIndex for usize {
5347    #[inline]
5348    fn is_in_bounds(&self, len: usize) -> bool {
5349        *self < len
5350    }
5351
5352    #[inline]
5353    fn is_overlapping(&self, other: &Self) -> bool {
5354        *self == *other
5355    }
5356}
5357
5358#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5359// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5360unsafe impl GetDisjointMutIndex for Range<usize> {
5361    #[inline]
5362    fn is_in_bounds(&self, len: usize) -> bool {
5363        (self.start <= self.end) & (self.end <= len)
5364    }
5365
5366    #[inline]
5367    fn is_overlapping(&self, other: &Self) -> bool {
5368        (self.start < other.end) & (other.start < self.end)
5369    }
5370}
5371
5372#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5373// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5374unsafe impl GetDisjointMutIndex for RangeInclusive<usize> {
5375    #[inline]
5376    fn is_in_bounds(&self, len: usize) -> bool {
5377        (self.start <= self.end) & (self.end < len)
5378    }
5379
5380    #[inline]
5381    fn is_overlapping(&self, other: &Self) -> bool {
5382        (self.start <= other.end) & (other.start <= self.end)
5383    }
5384}
5385
5386#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5387// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5388unsafe impl GetDisjointMutIndex for range::Range<usize> {
5389    #[inline]
5390    fn is_in_bounds(&self, len: usize) -> bool {
5391        Range::from(*self).is_in_bounds(len)
5392    }
5393
5394    #[inline]
5395    fn is_overlapping(&self, other: &Self) -> bool {
5396        Range::from(*self).is_overlapping(&Range::from(*other))
5397    }
5398}
5399
5400#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5401// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5402unsafe impl GetDisjointMutIndex for range::RangeInclusive<usize> {
5403    #[inline]
5404    fn is_in_bounds(&self, len: usize) -> bool {
5405        RangeInclusive::from(*self).is_in_bounds(len)
5406    }
5407
5408    #[inline]
5409    fn is_overlapping(&self, other: &Self) -> bool {
5410        RangeInclusive::from(*self).is_overlapping(&RangeInclusive::from(*other))
5411    }
5412}