core/slice/
mod.rs

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