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