core/slice/
mod.rs

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