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