Skip to main content

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