Skip to main content

core/slice/
mod.rs

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