]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/mod.rs
add `slice::swap_unchecked`
[rust.git] / library / core / src / slice / mod.rs
1 //! Slice management and manipulation.
2 //!
3 //! For more details see [`std::slice`].
4 //!
5 //! [`std::slice`]: ../../std/slice/index.html
6
7 #![stable(feature = "rust1", since = "1.0.0")]
8
9 use crate::cmp::Ordering::{self, Greater, Less};
10 use crate::marker::Copy;
11 use crate::mem;
12 use crate::num::NonZeroUsize;
13 use crate::ops::{FnMut, Range, RangeBounds};
14 use crate::option::Option;
15 use crate::option::Option::{None, Some};
16 use crate::ptr;
17 use crate::result::Result;
18 use crate::result::Result::{Err, Ok};
19 use crate::slice;
20
21 #[unstable(
22     feature = "slice_internals",
23     issue = "none",
24     reason = "exposed from core to be reused in std; use the memchr crate"
25 )]
26 /// Pure rust memchr implementation, taken from rust-memchr
27 pub mod memchr;
28
29 mod ascii;
30 mod cmp;
31 mod index;
32 mod iter;
33 mod raw;
34 mod rotate;
35 mod sort;
36 mod specialize;
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub use iter::{Chunks, ChunksMut, Windows};
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter::{Iter, IterMut};
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
44
45 #[stable(feature = "slice_rsplit", since = "1.27.0")]
46 pub use iter::{RSplit, RSplitMut};
47
48 #[stable(feature = "chunks_exact", since = "1.31.0")]
49 pub use iter::{ChunksExact, ChunksExactMut};
50
51 #[stable(feature = "rchunks", since = "1.31.0")]
52 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
53
54 #[unstable(feature = "array_chunks", issue = "74985")]
55 pub use iter::{ArrayChunks, ArrayChunksMut};
56
57 #[unstable(feature = "array_windows", issue = "75027")]
58 pub use iter::ArrayWindows;
59
60 #[unstable(feature = "slice_group_by", issue = "80552")]
61 pub use iter::{GroupBy, GroupByMut};
62
63 #[stable(feature = "split_inclusive", since = "1.51.0")]
64 pub use iter::{SplitInclusive, SplitInclusiveMut};
65
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use raw::{from_raw_parts, from_raw_parts_mut};
68
69 #[stable(feature = "from_ref", since = "1.28.0")]
70 pub use raw::{from_mut, from_ref};
71
72 // This function is public only because there is no other way to unit test heapsort.
73 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
74 pub use sort::heapsort;
75
76 #[stable(feature = "slice_get_slice", since = "1.28.0")]
77 pub use index::SliceIndex;
78
79 #[unstable(feature = "slice_range", issue = "76393")]
80 pub use index::range;
81
82 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
83 pub use ascii::EscapeAscii;
84
85 #[lang = "slice"]
86 #[cfg(not(test))]
87 impl<T> [T] {
88     /// Returns the number of elements in the slice.
89     ///
90     /// # Examples
91     ///
92     /// ```
93     /// let a = [1, 2, 3];
94     /// assert_eq!(a.len(), 3);
95     /// ```
96     #[lang = "slice_len_fn"]
97     #[stable(feature = "rust1", since = "1.0.0")]
98     #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
99     #[inline]
100     // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
101     pub const fn len(&self) -> usize {
102         // FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable.
103         // As of this writing this causes a "Const-stable functions can only call other
104         // const-stable functions" error.
105
106         // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
107         // and PtrComponents<T> have the same memory layouts. Only std can make this
108         // guarantee.
109         unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata }
110     }
111
112     /// Returns `true` if the slice has a length of 0.
113     ///
114     /// # Examples
115     ///
116     /// ```
117     /// let a = [1, 2, 3];
118     /// assert!(!a.is_empty());
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
122     #[inline]
123     pub const fn is_empty(&self) -> bool {
124         self.len() == 0
125     }
126
127     /// Returns the first element of the slice, or `None` if it is empty.
128     ///
129     /// # Examples
130     ///
131     /// ```
132     /// let v = [10, 40, 30];
133     /// assert_eq!(Some(&10), v.first());
134     ///
135     /// let w: &[i32] = &[];
136     /// assert_eq!(None, w.first());
137     /// ```
138     #[stable(feature = "rust1", since = "1.0.0")]
139     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
140     #[inline]
141     pub const fn first(&self) -> Option<&T> {
142         if let [first, ..] = self { Some(first) } else { None }
143     }
144
145     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
146     ///
147     /// # Examples
148     ///
149     /// ```
150     /// let x = &mut [0, 1, 2];
151     ///
152     /// if let Some(first) = x.first_mut() {
153     ///     *first = 5;
154     /// }
155     /// assert_eq!(x, &[5, 1, 2]);
156     /// ```
157     #[stable(feature = "rust1", since = "1.0.0")]
158     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
159     #[inline]
160     pub const fn first_mut(&mut self) -> Option<&mut T> {
161         if let [first, ..] = self { Some(first) } else { None }
162     }
163
164     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
165     ///
166     /// # Examples
167     ///
168     /// ```
169     /// let x = &[0, 1, 2];
170     ///
171     /// if let Some((first, elements)) = x.split_first() {
172     ///     assert_eq!(first, &0);
173     ///     assert_eq!(elements, &[1, 2]);
174     /// }
175     /// ```
176     #[stable(feature = "slice_splits", since = "1.5.0")]
177     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
178     #[inline]
179     pub const fn split_first(&self) -> Option<(&T, &[T])> {
180         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
181     }
182
183     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
184     ///
185     /// # Examples
186     ///
187     /// ```
188     /// let x = &mut [0, 1, 2];
189     ///
190     /// if let Some((first, elements)) = x.split_first_mut() {
191     ///     *first = 3;
192     ///     elements[0] = 4;
193     ///     elements[1] = 5;
194     /// }
195     /// assert_eq!(x, &[3, 4, 5]);
196     /// ```
197     #[stable(feature = "slice_splits", since = "1.5.0")]
198     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
199     #[inline]
200     pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
201         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
202     }
203
204     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// let x = &[0, 1, 2];
210     ///
211     /// if let Some((last, elements)) = x.split_last() {
212     ///     assert_eq!(last, &2);
213     ///     assert_eq!(elements, &[0, 1]);
214     /// }
215     /// ```
216     #[stable(feature = "slice_splits", since = "1.5.0")]
217     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
218     #[inline]
219     pub const fn split_last(&self) -> Option<(&T, &[T])> {
220         if let [init @ .., last] = self { Some((last, init)) } else { None }
221     }
222
223     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
224     ///
225     /// # Examples
226     ///
227     /// ```
228     /// let x = &mut [0, 1, 2];
229     ///
230     /// if let Some((last, elements)) = x.split_last_mut() {
231     ///     *last = 3;
232     ///     elements[0] = 4;
233     ///     elements[1] = 5;
234     /// }
235     /// assert_eq!(x, &[4, 5, 3]);
236     /// ```
237     #[stable(feature = "slice_splits", since = "1.5.0")]
238     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
239     #[inline]
240     pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
241         if let [init @ .., last] = self { Some((last, init)) } else { None }
242     }
243
244     /// Returns the last element of the slice, or `None` if it is empty.
245     ///
246     /// # Examples
247     ///
248     /// ```
249     /// let v = [10, 40, 30];
250     /// assert_eq!(Some(&30), v.last());
251     ///
252     /// let w: &[i32] = &[];
253     /// assert_eq!(None, w.last());
254     /// ```
255     #[stable(feature = "rust1", since = "1.0.0")]
256     #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
257     #[inline]
258     pub const fn last(&self) -> Option<&T> {
259         if let [.., last] = self { Some(last) } else { None }
260     }
261
262     /// Returns a mutable pointer to the last item in the slice.
263     ///
264     /// # Examples
265     ///
266     /// ```
267     /// let x = &mut [0, 1, 2];
268     ///
269     /// if let Some(last) = x.last_mut() {
270     ///     *last = 10;
271     /// }
272     /// assert_eq!(x, &[0, 1, 10]);
273     /// ```
274     #[stable(feature = "rust1", since = "1.0.0")]
275     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
276     #[inline]
277     pub const fn last_mut(&mut self) -> Option<&mut T> {
278         if let [.., last] = self { Some(last) } else { None }
279     }
280
281     /// Returns a reference to an element or subslice depending on the type of
282     /// index.
283     ///
284     /// - If given a position, returns a reference to the element at that
285     ///   position or `None` if out of bounds.
286     /// - If given a range, returns the subslice corresponding to that range,
287     ///   or `None` if out of bounds.
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// let v = [10, 40, 30];
293     /// assert_eq!(Some(&40), v.get(1));
294     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
295     /// assert_eq!(None, v.get(3));
296     /// assert_eq!(None, v.get(0..4));
297     /// ```
298     #[stable(feature = "rust1", since = "1.0.0")]
299     #[inline]
300     pub fn get<I>(&self, index: I) -> Option<&I::Output>
301     where
302         I: SliceIndex<Self>,
303     {
304         index.get(self)
305     }
306
307     /// Returns a mutable reference to an element or subslice depending on the
308     /// type of index (see [`get`]) or `None` if the index is out of bounds.
309     ///
310     /// [`get`]: slice::get
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// let x = &mut [0, 1, 2];
316     ///
317     /// if let Some(elem) = x.get_mut(1) {
318     ///     *elem = 42;
319     /// }
320     /// assert_eq!(x, &[0, 42, 2]);
321     /// ```
322     #[stable(feature = "rust1", since = "1.0.0")]
323     #[inline]
324     pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
325     where
326         I: SliceIndex<Self>,
327     {
328         index.get_mut(self)
329     }
330
331     /// Returns a reference to an element or subslice, without doing bounds
332     /// checking.
333     ///
334     /// For a safe alternative see [`get`].
335     ///
336     /// # Safety
337     ///
338     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
339     /// even if the resulting reference is not used.
340     ///
341     /// [`get`]: slice::get
342     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// let x = &[1, 2, 4];
348     ///
349     /// unsafe {
350     ///     assert_eq!(x.get_unchecked(1), &2);
351     /// }
352     /// ```
353     #[stable(feature = "rust1", since = "1.0.0")]
354     #[inline]
355     pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
356     where
357         I: SliceIndex<Self>,
358     {
359         // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
360         // the slice is dereferencable because `self` is a safe reference.
361         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
362         unsafe { &*index.get_unchecked(self) }
363     }
364
365     /// Returns a mutable reference to an element or subslice, without doing
366     /// bounds checking.
367     ///
368     /// For a safe alternative see [`get_mut`].
369     ///
370     /// # Safety
371     ///
372     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
373     /// even if the resulting reference is not used.
374     ///
375     /// [`get_mut`]: slice::get_mut
376     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
377     ///
378     /// # Examples
379     ///
380     /// ```
381     /// let x = &mut [1, 2, 4];
382     ///
383     /// unsafe {
384     ///     let elem = x.get_unchecked_mut(1);
385     ///     *elem = 13;
386     /// }
387     /// assert_eq!(x, &[1, 13, 4]);
388     /// ```
389     #[stable(feature = "rust1", since = "1.0.0")]
390     #[inline]
391     pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
392     where
393         I: SliceIndex<Self>,
394     {
395         // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
396         // the slice is dereferencable because `self` is a safe reference.
397         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
398         unsafe { &mut *index.get_unchecked_mut(self) }
399     }
400
401     /// Returns a raw pointer to the slice's buffer.
402     ///
403     /// The caller must ensure that the slice outlives the pointer this
404     /// function returns, or else it will end up pointing to garbage.
405     ///
406     /// The caller must also ensure that the memory the pointer (non-transitively) points to
407     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
408     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
409     ///
410     /// Modifying the container referenced by this slice may cause its buffer
411     /// to be reallocated, which would also make any pointers to it invalid.
412     ///
413     /// # Examples
414     ///
415     /// ```
416     /// let x = &[1, 2, 4];
417     /// let x_ptr = x.as_ptr();
418     ///
419     /// unsafe {
420     ///     for i in 0..x.len() {
421     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
422     ///     }
423     /// }
424     /// ```
425     ///
426     /// [`as_mut_ptr`]: slice::as_mut_ptr
427     #[stable(feature = "rust1", since = "1.0.0")]
428     #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
429     #[inline]
430     pub const fn as_ptr(&self) -> *const T {
431         self as *const [T] as *const T
432     }
433
434     /// Returns an unsafe mutable pointer to the slice's buffer.
435     ///
436     /// The caller must ensure that the slice outlives the pointer this
437     /// function returns, or else it will end up pointing to garbage.
438     ///
439     /// Modifying the container referenced by this slice may cause its buffer
440     /// to be reallocated, which would also make any pointers to it invalid.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// let x = &mut [1, 2, 4];
446     /// let x_ptr = x.as_mut_ptr();
447     ///
448     /// unsafe {
449     ///     for i in 0..x.len() {
450     ///         *x_ptr.add(i) += 2;
451     ///     }
452     /// }
453     /// assert_eq!(x, &[3, 4, 6]);
454     /// ```
455     #[stable(feature = "rust1", since = "1.0.0")]
456     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
457     #[inline]
458     pub const fn as_mut_ptr(&mut self) -> *mut T {
459         self as *mut [T] as *mut T
460     }
461
462     /// Returns the two raw pointers spanning the slice.
463     ///
464     /// The returned range is half-open, which means that the end pointer
465     /// points *one past* the last element of the slice. This way, an empty
466     /// slice is represented by two equal pointers, and the difference between
467     /// the two pointers represents the size of the slice.
468     ///
469     /// See [`as_ptr`] for warnings on using these pointers. The end pointer
470     /// requires extra caution, as it does not point to a valid element in the
471     /// slice.
472     ///
473     /// This function is useful for interacting with foreign interfaces which
474     /// use two pointers to refer to a range of elements in memory, as is
475     /// common in C++.
476     ///
477     /// It can also be useful to check if a pointer to an element refers to an
478     /// element of this slice:
479     ///
480     /// ```
481     /// let a = [1, 2, 3];
482     /// let x = &a[1] as *const _;
483     /// let y = &5 as *const _;
484     ///
485     /// assert!(a.as_ptr_range().contains(&x));
486     /// assert!(!a.as_ptr_range().contains(&y));
487     /// ```
488     ///
489     /// [`as_ptr`]: slice::as_ptr
490     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
491     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
492     #[inline]
493     pub const fn as_ptr_range(&self) -> Range<*const T> {
494         let start = self.as_ptr();
495         // SAFETY: The `add` here is safe, because:
496         //
497         //   - Both pointers are part of the same object, as pointing directly
498         //     past the object also counts.
499         //
500         //   - The size of the slice is never larger than isize::MAX bytes, as
501         //     noted here:
502         //       - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
503         //       - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
504         //       - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
505         //     (This doesn't seem normative yet, but the very same assumption is
506         //     made in many places, including the Index implementation of slices.)
507         //
508         //   - There is no wrapping around involved, as slices do not wrap past
509         //     the end of the address space.
510         //
511         // See the documentation of pointer::add.
512         let end = unsafe { start.add(self.len()) };
513         start..end
514     }
515
516     /// Returns the two unsafe mutable pointers spanning the slice.
517     ///
518     /// The returned range is half-open, which means that the end pointer
519     /// points *one past* the last element of the slice. This way, an empty
520     /// slice is represented by two equal pointers, and the difference between
521     /// the two pointers represents the size of the slice.
522     ///
523     /// See [`as_mut_ptr`] for warnings on using these pointers. The end
524     /// pointer requires extra caution, as it does not point to a valid element
525     /// in the slice.
526     ///
527     /// This function is useful for interacting with foreign interfaces which
528     /// use two pointers to refer to a range of elements in memory, as is
529     /// common in C++.
530     ///
531     /// [`as_mut_ptr`]: slice::as_mut_ptr
532     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
533     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
534     #[inline]
535     pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
536         let start = self.as_mut_ptr();
537         // SAFETY: See as_ptr_range() above for why `add` here is safe.
538         let end = unsafe { start.add(self.len()) };
539         start..end
540     }
541
542     /// Swaps two elements in the slice.
543     ///
544     /// # Arguments
545     ///
546     /// * a - The index of the first element
547     /// * b - The index of the second element
548     ///
549     /// # Panics
550     ///
551     /// Panics if `a` or `b` are out of bounds.
552     ///
553     /// # Examples
554     ///
555     /// ```
556     /// let mut v = ["a", "b", "c", "d"];
557     /// v.swap(1, 3);
558     /// assert!(v == ["a", "d", "c", "b"]);
559     /// ```
560     #[stable(feature = "rust1", since = "1.0.0")]
561     #[inline]
562     pub fn swap(&mut self, a: usize, b: usize) {
563         assert!(a < self.len());
564         assert!(b < self.len());
565         // SAFETY: we just checked that both `a` and `b` are in bounds
566         unsafe { self.swap_unchecked(a, b) }
567     }
568
569     /// Swaps two elements in the slice, without doing bounds checking.
570     ///
571     /// For a safe alternative see [`swap`].
572     ///
573     /// # Arguments
574     ///
575     /// * a - The index of the first element
576     /// * b - The index of the second element
577     ///
578     /// # Safety
579     ///
580     /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
581     /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
582     ///
583     /// # Examples
584     ///
585     /// ```
586     /// let mut v = ["a", "b", "c", "d"];
587     /// // SAFETY: we know that 1 and 3 are both indices of the slice
588     /// unsafe { v.swap_unchecked(1, 3) };
589     /// assert!(v == ["a", "d", "c", "b"]);
590     /// ```
591     ///
592     /// [`swap`]: slice::swap
593     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
594     #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
595     pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
596         debug_assert!(a < self.len());
597         debug_assert!(b < self.len());
598         let ptr = self.as_mut_ptr();
599         // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
600         unsafe {
601             ptr::swap(ptr.add(a), ptr.add(b));
602         }
603     }
604
605     /// Reverses the order of elements in the slice, in place.
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// let mut v = [1, 2, 3];
611     /// v.reverse();
612     /// assert!(v == [3, 2, 1]);
613     /// ```
614     #[stable(feature = "rust1", since = "1.0.0")]
615     #[inline]
616     pub fn reverse(&mut self) {
617         let mut i: usize = 0;
618         let ln = self.len();
619
620         // For very small types, all the individual reads in the normal
621         // path perform poorly.  We can do better, given efficient unaligned
622         // load/store, by loading a larger chunk and reversing a register.
623
624         // Ideally LLVM would do this for us, as it knows better than we do
625         // whether unaligned reads are efficient (since that changes between
626         // different ARM versions, for example) and what the best chunk size
627         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
628         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
629         // is troublesome because the sides can be aligned differently --
630         // will be, when the length is odd -- so there's no way of emitting
631         // pre- and postludes to use fully-aligned SIMD in the middle.)
632
633         let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
634
635         if fast_unaligned && mem::size_of::<T>() == 1 {
636             // Use the llvm.bswap intrinsic to reverse u8s in a usize
637             let chunk = mem::size_of::<usize>();
638             while i + chunk - 1 < ln / 2 {
639                 // SAFETY: There are several things to check here:
640                 //
641                 // - Note that `chunk` is either 4 or 8 due to the cfg check
642                 //   above. So `chunk - 1` is positive.
643                 // - Indexing with index `i` is fine as the loop check guarantees
644                 //   `i + chunk - 1 < ln / 2`
645                 //   <=> `i < ln / 2 - (chunk - 1) < ln / 2 < ln`.
646                 // - Indexing with index `ln - i - chunk = ln - (i + chunk)` is fine:
647                 //   - `i + chunk > 0` is trivially true.
648                 //   - The loop check guarantees:
649                 //     `i + chunk - 1 < ln / 2`
650                 //     <=> `i + chunk ≤ ln / 2 ≤ ln`, thus subtraction does not underflow.
651                 // - The `read_unaligned` and `write_unaligned` calls are fine:
652                 //   - `pa` points to index `i` where `i < ln / 2 - (chunk - 1)`
653                 //     (see above) and `pb` points to index `ln - i - chunk`, so
654                 //     both are at least `chunk`
655                 //     many bytes away from the end of `self`.
656                 //   - Any initialized memory is valid `usize`.
657                 unsafe {
658                     let ptr = self.as_mut_ptr();
659                     let pa = ptr.add(i);
660                     let pb = ptr.add(ln - i - chunk);
661                     let va = ptr::read_unaligned(pa as *mut usize);
662                     let vb = ptr::read_unaligned(pb as *mut usize);
663                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
664                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
665                 }
666                 i += chunk;
667             }
668         }
669
670         if fast_unaligned && mem::size_of::<T>() == 2 {
671             // Use rotate-by-16 to reverse u16s in a u32
672             let chunk = mem::size_of::<u32>() / 2;
673             while i + chunk - 1 < ln / 2 {
674                 // SAFETY: An unaligned u32 can be read from `i` if `i + 1 < ln`
675                 // (and obviously `i < ln`), because each element is 2 bytes and
676                 // we're reading 4.
677                 //
678                 // `i + chunk - 1 < ln / 2` # while condition
679                 // `i + 2 - 1 < ln / 2`
680                 // `i + 1 < ln / 2`
681                 //
682                 // Since it's less than the length divided by 2, then it must be
683                 // in bounds.
684                 //
685                 // This also means that the condition `0 < i + chunk <= ln` is
686                 // always respected, ensuring the `pb` pointer can be used
687                 // safely.
688                 unsafe {
689                     let ptr = self.as_mut_ptr();
690                     let pa = ptr.add(i);
691                     let pb = ptr.add(ln - i - chunk);
692                     let va = ptr::read_unaligned(pa as *mut u32);
693                     let vb = ptr::read_unaligned(pb as *mut u32);
694                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
695                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
696                 }
697                 i += chunk;
698             }
699         }
700
701         while i < ln / 2 {
702             // SAFETY: `i` is inferior to half the length of the slice so
703             // accessing `i` and `ln - i - 1` is safe (`i` starts at 0 and
704             // will not go further than `ln / 2 - 1`).
705             // The resulting pointers `pa` and `pb` are therefore valid and
706             // aligned, and can be read from and written to.
707             unsafe {
708                 // Unsafe swap to avoid the bounds check in safe swap.
709                 let ptr = self.as_mut_ptr();
710                 let pa = ptr.add(i);
711                 let pb = ptr.add(ln - i - 1);
712                 ptr::swap(pa, pb);
713             }
714             i += 1;
715         }
716     }
717
718     /// Returns an iterator over the slice.
719     ///
720     /// # Examples
721     ///
722     /// ```
723     /// let x = &[1, 2, 4];
724     /// let mut iterator = x.iter();
725     ///
726     /// assert_eq!(iterator.next(), Some(&1));
727     /// assert_eq!(iterator.next(), Some(&2));
728     /// assert_eq!(iterator.next(), Some(&4));
729     /// assert_eq!(iterator.next(), None);
730     /// ```
731     #[stable(feature = "rust1", since = "1.0.0")]
732     #[inline]
733     pub fn iter(&self) -> Iter<'_, T> {
734         Iter::new(self)
735     }
736
737     /// Returns an iterator that allows modifying each value.
738     ///
739     /// # Examples
740     ///
741     /// ```
742     /// let x = &mut [1, 2, 4];
743     /// for elem in x.iter_mut() {
744     ///     *elem += 2;
745     /// }
746     /// assert_eq!(x, &[3, 4, 6]);
747     /// ```
748     #[stable(feature = "rust1", since = "1.0.0")]
749     #[inline]
750     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
751         IterMut::new(self)
752     }
753
754     /// Returns an iterator over all contiguous windows of length
755     /// `size`. The windows overlap. If the slice is shorter than
756     /// `size`, the iterator returns no values.
757     ///
758     /// # Panics
759     ///
760     /// Panics if `size` is 0.
761     ///
762     /// # Examples
763     ///
764     /// ```
765     /// let slice = ['r', 'u', 's', 't'];
766     /// let mut iter = slice.windows(2);
767     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
768     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
769     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
770     /// assert!(iter.next().is_none());
771     /// ```
772     ///
773     /// If the slice is shorter than `size`:
774     ///
775     /// ```
776     /// let slice = ['f', 'o', 'o'];
777     /// let mut iter = slice.windows(4);
778     /// assert!(iter.next().is_none());
779     /// ```
780     #[stable(feature = "rust1", since = "1.0.0")]
781     #[inline]
782     pub fn windows(&self, size: usize) -> Windows<'_, T> {
783         let size = NonZeroUsize::new(size).expect("size is zero");
784         Windows::new(self, size)
785     }
786
787     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
788     /// beginning of the slice.
789     ///
790     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
791     /// slice, then the last chunk will not have length `chunk_size`.
792     ///
793     /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
794     /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
795     /// slice.
796     ///
797     /// # Panics
798     ///
799     /// Panics if `chunk_size` is 0.
800     ///
801     /// # Examples
802     ///
803     /// ```
804     /// let slice = ['l', 'o', 'r', 'e', 'm'];
805     /// let mut iter = slice.chunks(2);
806     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
807     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
808     /// assert_eq!(iter.next().unwrap(), &['m']);
809     /// assert!(iter.next().is_none());
810     /// ```
811     ///
812     /// [`chunks_exact`]: slice::chunks_exact
813     /// [`rchunks`]: slice::rchunks
814     #[stable(feature = "rust1", since = "1.0.0")]
815     #[inline]
816     pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
817         assert_ne!(chunk_size, 0);
818         Chunks::new(self, chunk_size)
819     }
820
821     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
822     /// beginning of the slice.
823     ///
824     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
825     /// length of the slice, then the last chunk will not have length `chunk_size`.
826     ///
827     /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
828     /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
829     /// the end of the slice.
830     ///
831     /// # Panics
832     ///
833     /// Panics if `chunk_size` is 0.
834     ///
835     /// # Examples
836     ///
837     /// ```
838     /// let v = &mut [0, 0, 0, 0, 0];
839     /// let mut count = 1;
840     ///
841     /// for chunk in v.chunks_mut(2) {
842     ///     for elem in chunk.iter_mut() {
843     ///         *elem += count;
844     ///     }
845     ///     count += 1;
846     /// }
847     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
848     /// ```
849     ///
850     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
851     /// [`rchunks_mut`]: slice::rchunks_mut
852     #[stable(feature = "rust1", since = "1.0.0")]
853     #[inline]
854     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
855         assert_ne!(chunk_size, 0);
856         ChunksMut::new(self, chunk_size)
857     }
858
859     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
860     /// beginning of the slice.
861     ///
862     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
863     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
864     /// from the `remainder` function of the iterator.
865     ///
866     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
867     /// resulting code better than in the case of [`chunks`].
868     ///
869     /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
870     /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
871     ///
872     /// # Panics
873     ///
874     /// Panics if `chunk_size` is 0.
875     ///
876     /// # Examples
877     ///
878     /// ```
879     /// let slice = ['l', 'o', 'r', 'e', 'm'];
880     /// let mut iter = slice.chunks_exact(2);
881     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
882     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
883     /// assert!(iter.next().is_none());
884     /// assert_eq!(iter.remainder(), &['m']);
885     /// ```
886     ///
887     /// [`chunks`]: slice::chunks
888     /// [`rchunks_exact`]: slice::rchunks_exact
889     #[stable(feature = "chunks_exact", since = "1.31.0")]
890     #[inline]
891     pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
892         assert_ne!(chunk_size, 0);
893         ChunksExact::new(self, chunk_size)
894     }
895
896     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
897     /// beginning of the slice.
898     ///
899     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
900     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
901     /// retrieved from the `into_remainder` function of the iterator.
902     ///
903     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
904     /// resulting code better than in the case of [`chunks_mut`].
905     ///
906     /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
907     /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
908     /// the slice.
909     ///
910     /// # Panics
911     ///
912     /// Panics if `chunk_size` is 0.
913     ///
914     /// # Examples
915     ///
916     /// ```
917     /// let v = &mut [0, 0, 0, 0, 0];
918     /// let mut count = 1;
919     ///
920     /// for chunk in v.chunks_exact_mut(2) {
921     ///     for elem in chunk.iter_mut() {
922     ///         *elem += count;
923     ///     }
924     ///     count += 1;
925     /// }
926     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
927     /// ```
928     ///
929     /// [`chunks_mut`]: slice::chunks_mut
930     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
931     #[stable(feature = "chunks_exact", since = "1.31.0")]
932     #[inline]
933     pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
934         assert_ne!(chunk_size, 0);
935         ChunksExactMut::new(self, chunk_size)
936     }
937
938     /// Splits the slice into a slice of `N`-element arrays,
939     /// assuming that there's no remainder.
940     ///
941     /// # Safety
942     ///
943     /// This may only be called when
944     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
945     /// - `N != 0`.
946     ///
947     /// # Examples
948     ///
949     /// ```
950     /// #![feature(slice_as_chunks)]
951     /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
952     /// let chunks: &[[char; 1]] =
953     ///     // SAFETY: 1-element chunks never have remainder
954     ///     unsafe { slice.as_chunks_unchecked() };
955     /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
956     /// let chunks: &[[char; 3]] =
957     ///     // SAFETY: The slice length (6) is a multiple of 3
958     ///     unsafe { slice.as_chunks_unchecked() };
959     /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
960     ///
961     /// // These would be unsound:
962     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
963     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
964     /// ```
965     #[unstable(feature = "slice_as_chunks", issue = "74985")]
966     #[inline]
967     pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
968         debug_assert_ne!(N, 0);
969         debug_assert_eq!(self.len() % N, 0);
970         let new_len =
971             // SAFETY: Our precondition is exactly what's needed to call this
972             unsafe { crate::intrinsics::exact_div(self.len(), N) };
973         // SAFETY: We cast a slice of `new_len * N` elements into
974         // a slice of `new_len` many `N` elements chunks.
975         unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
976     }
977
978     /// Splits the slice into a slice of `N`-element arrays,
979     /// starting at the beginning of the slice,
980     /// and a remainder slice with length strictly less than `N`.
981     ///
982     /// # Panics
983     ///
984     /// Panics if `N` is 0. This check will most probably get changed to a compile time
985     /// error before this method gets stabilized.
986     ///
987     /// # Examples
988     ///
989     /// ```
990     /// #![feature(slice_as_chunks)]
991     /// let slice = ['l', 'o', 'r', 'e', 'm'];
992     /// let (chunks, remainder) = slice.as_chunks();
993     /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
994     /// assert_eq!(remainder, &['m']);
995     /// ```
996     #[unstable(feature = "slice_as_chunks", issue = "74985")]
997     #[inline]
998     pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
999         assert_ne!(N, 0);
1000         let len = self.len() / N;
1001         let (multiple_of_n, remainder) = self.split_at(len * N);
1002         // SAFETY: We already panicked for zero, and ensured by construction
1003         // that the length of the subslice is a multiple of N.
1004         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1005         (array_slice, remainder)
1006     }
1007
1008     /// Splits the slice into a slice of `N`-element arrays,
1009     /// starting at the end of the slice,
1010     /// and a remainder slice with length strictly less than `N`.
1011     ///
1012     /// # Panics
1013     ///
1014     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1015     /// error before this method gets stabilized.
1016     ///
1017     /// # Examples
1018     ///
1019     /// ```
1020     /// #![feature(slice_as_chunks)]
1021     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1022     /// let (remainder, chunks) = slice.as_rchunks();
1023     /// assert_eq!(remainder, &['l']);
1024     /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1025     /// ```
1026     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1027     #[inline]
1028     pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1029         assert_ne!(N, 0);
1030         let len = self.len() / N;
1031         let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1032         // SAFETY: We already panicked for zero, and ensured by construction
1033         // that the length of the subslice is a multiple of N.
1034         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1035         (remainder, array_slice)
1036     }
1037
1038     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1039     /// beginning of the slice.
1040     ///
1041     /// The chunks are array references and do not overlap. If `N` does not divide the
1042     /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1043     /// retrieved from the `remainder` function of the iterator.
1044     ///
1045     /// This method is the const generic equivalent of [`chunks_exact`].
1046     ///
1047     /// # Panics
1048     ///
1049     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1050     /// error before this method gets stabilized.
1051     ///
1052     /// # Examples
1053     ///
1054     /// ```
1055     /// #![feature(array_chunks)]
1056     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1057     /// let mut iter = slice.array_chunks();
1058     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1059     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1060     /// assert!(iter.next().is_none());
1061     /// assert_eq!(iter.remainder(), &['m']);
1062     /// ```
1063     ///
1064     /// [`chunks_exact`]: slice::chunks_exact
1065     #[unstable(feature = "array_chunks", issue = "74985")]
1066     #[inline]
1067     pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1068         assert_ne!(N, 0);
1069         ArrayChunks::new(self)
1070     }
1071
1072     /// Splits the slice into a slice of `N`-element arrays,
1073     /// assuming that there's no remainder.
1074     ///
1075     /// # Safety
1076     ///
1077     /// This may only be called when
1078     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1079     /// - `N != 0`.
1080     ///
1081     /// # Examples
1082     ///
1083     /// ```
1084     /// #![feature(slice_as_chunks)]
1085     /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1086     /// let chunks: &mut [[char; 1]] =
1087     ///     // SAFETY: 1-element chunks never have remainder
1088     ///     unsafe { slice.as_chunks_unchecked_mut() };
1089     /// chunks[0] = ['L'];
1090     /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1091     /// let chunks: &mut [[char; 3]] =
1092     ///     // SAFETY: The slice length (6) is a multiple of 3
1093     ///     unsafe { slice.as_chunks_unchecked_mut() };
1094     /// chunks[1] = ['a', 'x', '?'];
1095     /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1096     ///
1097     /// // These would be unsound:
1098     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1099     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1100     /// ```
1101     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1102     #[inline]
1103     pub unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1104         debug_assert_ne!(N, 0);
1105         debug_assert_eq!(self.len() % N, 0);
1106         let new_len =
1107             // SAFETY: Our precondition is exactly what's needed to call this
1108             unsafe { crate::intrinsics::exact_div(self.len(), N) };
1109         // SAFETY: We cast a slice of `new_len * N` elements into
1110         // a slice of `new_len` many `N` elements chunks.
1111         unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1112     }
1113
1114     /// Splits the slice into a slice of `N`-element arrays,
1115     /// starting at the beginning of the slice,
1116     /// and a remainder slice with length strictly less than `N`.
1117     ///
1118     /// # Panics
1119     ///
1120     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1121     /// error before this method gets stabilized.
1122     ///
1123     /// # Examples
1124     ///
1125     /// ```
1126     /// #![feature(slice_as_chunks)]
1127     /// let v = &mut [0, 0, 0, 0, 0];
1128     /// let mut count = 1;
1129     ///
1130     /// let (chunks, remainder) = v.as_chunks_mut();
1131     /// remainder[0] = 9;
1132     /// for chunk in chunks {
1133     ///     *chunk = [count; 2];
1134     ///     count += 1;
1135     /// }
1136     /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1137     /// ```
1138     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1139     #[inline]
1140     pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1141         assert_ne!(N, 0);
1142         let len = self.len() / N;
1143         let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1144         // SAFETY: We already panicked for zero, and ensured by construction
1145         // that the length of the subslice is a multiple of N.
1146         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1147         (array_slice, remainder)
1148     }
1149
1150     /// Splits the slice into a slice of `N`-element arrays,
1151     /// starting at the end of the slice,
1152     /// and a remainder slice with length strictly less than `N`.
1153     ///
1154     /// # Panics
1155     ///
1156     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1157     /// error before this method gets stabilized.
1158     ///
1159     /// # Examples
1160     ///
1161     /// ```
1162     /// #![feature(slice_as_chunks)]
1163     /// let v = &mut [0, 0, 0, 0, 0];
1164     /// let mut count = 1;
1165     ///
1166     /// let (remainder, chunks) = v.as_rchunks_mut();
1167     /// remainder[0] = 9;
1168     /// for chunk in chunks {
1169     ///     *chunk = [count; 2];
1170     ///     count += 1;
1171     /// }
1172     /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1173     /// ```
1174     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1175     #[inline]
1176     pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1177         assert_ne!(N, 0);
1178         let len = self.len() / N;
1179         let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1180         // SAFETY: We already panicked for zero, and ensured by construction
1181         // that the length of the subslice is a multiple of N.
1182         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1183         (remainder, array_slice)
1184     }
1185
1186     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1187     /// beginning of the slice.
1188     ///
1189     /// The chunks are mutable array references and do not overlap. If `N` does not divide
1190     /// the length of the slice, then the last up to `N-1` elements will be omitted and
1191     /// can be retrieved from the `into_remainder` function of the iterator.
1192     ///
1193     /// This method is the const generic equivalent of [`chunks_exact_mut`].
1194     ///
1195     /// # Panics
1196     ///
1197     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1198     /// error before this method gets stabilized.
1199     ///
1200     /// # Examples
1201     ///
1202     /// ```
1203     /// #![feature(array_chunks)]
1204     /// let v = &mut [0, 0, 0, 0, 0];
1205     /// let mut count = 1;
1206     ///
1207     /// for chunk in v.array_chunks_mut() {
1208     ///     *chunk = [count; 2];
1209     ///     count += 1;
1210     /// }
1211     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1212     /// ```
1213     ///
1214     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1215     #[unstable(feature = "array_chunks", issue = "74985")]
1216     #[inline]
1217     pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1218         assert_ne!(N, 0);
1219         ArrayChunksMut::new(self)
1220     }
1221
1222     /// Returns an iterator over overlapping windows of `N` elements of  a slice,
1223     /// starting at the beginning of the slice.
1224     ///
1225     /// This is the const generic equivalent of [`windows`].
1226     ///
1227     /// If `N` is greater than the size of the slice, it will return no windows.
1228     ///
1229     /// # Panics
1230     ///
1231     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1232     /// error before this method gets stabilized.
1233     ///
1234     /// # Examples
1235     ///
1236     /// ```
1237     /// #![feature(array_windows)]
1238     /// let slice = [0, 1, 2, 3];
1239     /// let mut iter = slice.array_windows();
1240     /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1241     /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1242     /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1243     /// assert!(iter.next().is_none());
1244     /// ```
1245     ///
1246     /// [`windows`]: slice::windows
1247     #[unstable(feature = "array_windows", issue = "75027")]
1248     #[inline]
1249     pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1250         assert_ne!(N, 0);
1251         ArrayWindows::new(self)
1252     }
1253
1254     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1255     /// of the slice.
1256     ///
1257     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1258     /// slice, then the last chunk will not have length `chunk_size`.
1259     ///
1260     /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1261     /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1262     /// of the slice.
1263     ///
1264     /// # Panics
1265     ///
1266     /// Panics if `chunk_size` is 0.
1267     ///
1268     /// # Examples
1269     ///
1270     /// ```
1271     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1272     /// let mut iter = slice.rchunks(2);
1273     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1274     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1275     /// assert_eq!(iter.next().unwrap(), &['l']);
1276     /// assert!(iter.next().is_none());
1277     /// ```
1278     ///
1279     /// [`rchunks_exact`]: slice::rchunks_exact
1280     /// [`chunks`]: slice::chunks
1281     #[stable(feature = "rchunks", since = "1.31.0")]
1282     #[inline]
1283     pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1284         assert!(chunk_size != 0);
1285         RChunks::new(self, chunk_size)
1286     }
1287
1288     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1289     /// of the slice.
1290     ///
1291     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1292     /// length of the slice, then the last chunk will not have length `chunk_size`.
1293     ///
1294     /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1295     /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1296     /// beginning of the slice.
1297     ///
1298     /// # Panics
1299     ///
1300     /// Panics if `chunk_size` is 0.
1301     ///
1302     /// # Examples
1303     ///
1304     /// ```
1305     /// let v = &mut [0, 0, 0, 0, 0];
1306     /// let mut count = 1;
1307     ///
1308     /// for chunk in v.rchunks_mut(2) {
1309     ///     for elem in chunk.iter_mut() {
1310     ///         *elem += count;
1311     ///     }
1312     ///     count += 1;
1313     /// }
1314     /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1315     /// ```
1316     ///
1317     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1318     /// [`chunks_mut`]: slice::chunks_mut
1319     #[stable(feature = "rchunks", since = "1.31.0")]
1320     #[inline]
1321     pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1322         assert!(chunk_size != 0);
1323         RChunksMut::new(self, chunk_size)
1324     }
1325
1326     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1327     /// end of the slice.
1328     ///
1329     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1330     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1331     /// from the `remainder` function of the iterator.
1332     ///
1333     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1334     /// resulting code better than in the case of [`chunks`].
1335     ///
1336     /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1337     /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1338     /// slice.
1339     ///
1340     /// # Panics
1341     ///
1342     /// Panics if `chunk_size` is 0.
1343     ///
1344     /// # Examples
1345     ///
1346     /// ```
1347     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1348     /// let mut iter = slice.rchunks_exact(2);
1349     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1350     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1351     /// assert!(iter.next().is_none());
1352     /// assert_eq!(iter.remainder(), &['l']);
1353     /// ```
1354     ///
1355     /// [`chunks`]: slice::chunks
1356     /// [`rchunks`]: slice::rchunks
1357     /// [`chunks_exact`]: slice::chunks_exact
1358     #[stable(feature = "rchunks", since = "1.31.0")]
1359     #[inline]
1360     pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1361         assert!(chunk_size != 0);
1362         RChunksExact::new(self, chunk_size)
1363     }
1364
1365     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1366     /// of the slice.
1367     ///
1368     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1369     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1370     /// retrieved from the `into_remainder` function of the iterator.
1371     ///
1372     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1373     /// resulting code better than in the case of [`chunks_mut`].
1374     ///
1375     /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1376     /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1377     /// of the slice.
1378     ///
1379     /// # Panics
1380     ///
1381     /// Panics if `chunk_size` is 0.
1382     ///
1383     /// # Examples
1384     ///
1385     /// ```
1386     /// let v = &mut [0, 0, 0, 0, 0];
1387     /// let mut count = 1;
1388     ///
1389     /// for chunk in v.rchunks_exact_mut(2) {
1390     ///     for elem in chunk.iter_mut() {
1391     ///         *elem += count;
1392     ///     }
1393     ///     count += 1;
1394     /// }
1395     /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1396     /// ```
1397     ///
1398     /// [`chunks_mut`]: slice::chunks_mut
1399     /// [`rchunks_mut`]: slice::rchunks_mut
1400     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1401     #[stable(feature = "rchunks", since = "1.31.0")]
1402     #[inline]
1403     pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1404         assert!(chunk_size != 0);
1405         RChunksExactMut::new(self, chunk_size)
1406     }
1407
1408     /// Returns an iterator over the slice producing non-overlapping runs
1409     /// of elements using the predicate to separate them.
1410     ///
1411     /// The predicate is called on two elements following themselves,
1412     /// it means the predicate is called on `slice[0]` and `slice[1]`
1413     /// then on `slice[1]` and `slice[2]` and so on.
1414     ///
1415     /// # Examples
1416     ///
1417     /// ```
1418     /// #![feature(slice_group_by)]
1419     ///
1420     /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1421     ///
1422     /// let mut iter = slice.group_by(|a, b| a == b);
1423     ///
1424     /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1425     /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1426     /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1427     /// assert_eq!(iter.next(), None);
1428     /// ```
1429     ///
1430     /// This method can be used to extract the sorted subslices:
1431     ///
1432     /// ```
1433     /// #![feature(slice_group_by)]
1434     ///
1435     /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1436     ///
1437     /// let mut iter = slice.group_by(|a, b| a <= b);
1438     ///
1439     /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1440     /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1441     /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1442     /// assert_eq!(iter.next(), None);
1443     /// ```
1444     #[unstable(feature = "slice_group_by", issue = "80552")]
1445     #[inline]
1446     pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>
1447     where
1448         F: FnMut(&T, &T) -> bool,
1449     {
1450         GroupBy::new(self, pred)
1451     }
1452
1453     /// Returns an iterator over the slice producing non-overlapping mutable
1454     /// runs of elements using the predicate to separate them.
1455     ///
1456     /// The predicate is called on two elements following themselves,
1457     /// it means the predicate is called on `slice[0]` and `slice[1]`
1458     /// then on `slice[1]` and `slice[2]` and so on.
1459     ///
1460     /// # Examples
1461     ///
1462     /// ```
1463     /// #![feature(slice_group_by)]
1464     ///
1465     /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1466     ///
1467     /// let mut iter = slice.group_by_mut(|a, b| a == b);
1468     ///
1469     /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1470     /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1471     /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1472     /// assert_eq!(iter.next(), None);
1473     /// ```
1474     ///
1475     /// This method can be used to extract the sorted subslices:
1476     ///
1477     /// ```
1478     /// #![feature(slice_group_by)]
1479     ///
1480     /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1481     ///
1482     /// let mut iter = slice.group_by_mut(|a, b| a <= b);
1483     ///
1484     /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1485     /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1486     /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1487     /// assert_eq!(iter.next(), None);
1488     /// ```
1489     #[unstable(feature = "slice_group_by", issue = "80552")]
1490     #[inline]
1491     pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>
1492     where
1493         F: FnMut(&T, &T) -> bool,
1494     {
1495         GroupByMut::new(self, pred)
1496     }
1497
1498     /// Divides one slice into two at an index.
1499     ///
1500     /// The first will contain all indices from `[0, mid)` (excluding
1501     /// the index `mid` itself) and the second will contain all
1502     /// indices from `[mid, len)` (excluding the index `len` itself).
1503     ///
1504     /// # Panics
1505     ///
1506     /// Panics if `mid > len`.
1507     ///
1508     /// # Examples
1509     ///
1510     /// ```
1511     /// let v = [1, 2, 3, 4, 5, 6];
1512     ///
1513     /// {
1514     ///    let (left, right) = v.split_at(0);
1515     ///    assert_eq!(left, []);
1516     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1517     /// }
1518     ///
1519     /// {
1520     ///     let (left, right) = v.split_at(2);
1521     ///     assert_eq!(left, [1, 2]);
1522     ///     assert_eq!(right, [3, 4, 5, 6]);
1523     /// }
1524     ///
1525     /// {
1526     ///     let (left, right) = v.split_at(6);
1527     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1528     ///     assert_eq!(right, []);
1529     /// }
1530     /// ```
1531     #[stable(feature = "rust1", since = "1.0.0")]
1532     #[inline]
1533     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1534         assert!(mid <= self.len());
1535         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1536         // fulfills the requirements of `from_raw_parts_mut`.
1537         unsafe { self.split_at_unchecked(mid) }
1538     }
1539
1540     /// Divides one mutable slice into two at an index.
1541     ///
1542     /// The first will contain all indices from `[0, mid)` (excluding
1543     /// the index `mid` itself) and the second will contain all
1544     /// indices from `[mid, len)` (excluding the index `len` itself).
1545     ///
1546     /// # Panics
1547     ///
1548     /// Panics if `mid > len`.
1549     ///
1550     /// # Examples
1551     ///
1552     /// ```
1553     /// let mut v = [1, 0, 3, 0, 5, 6];
1554     /// let (left, right) = v.split_at_mut(2);
1555     /// assert_eq!(left, [1, 0]);
1556     /// assert_eq!(right, [3, 0, 5, 6]);
1557     /// left[1] = 2;
1558     /// right[1] = 4;
1559     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1560     /// ```
1561     #[stable(feature = "rust1", since = "1.0.0")]
1562     #[inline]
1563     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1564         assert!(mid <= self.len());
1565         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1566         // fulfills the requirements of `from_raw_parts_mut`.
1567         unsafe { self.split_at_mut_unchecked(mid) }
1568     }
1569
1570     /// Divides one slice into two at an index, without doing bounds checking.
1571     ///
1572     /// The first will contain all indices from `[0, mid)` (excluding
1573     /// the index `mid` itself) and the second will contain all
1574     /// indices from `[mid, len)` (excluding the index `len` itself).
1575     ///
1576     /// For a safe alternative see [`split_at`].
1577     ///
1578     /// # Safety
1579     ///
1580     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1581     /// even if the resulting reference is not used. The caller has to ensure that
1582     /// `0 <= mid <= self.len()`.
1583     ///
1584     /// [`split_at`]: slice::split_at
1585     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1586     ///
1587     /// # Examples
1588     ///
1589     /// ```
1590     /// #![feature(slice_split_at_unchecked)]
1591     ///
1592     /// let v = [1, 2, 3, 4, 5, 6];
1593     ///
1594     /// unsafe {
1595     ///    let (left, right) = v.split_at_unchecked(0);
1596     ///    assert_eq!(left, []);
1597     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1598     /// }
1599     ///
1600     /// unsafe {
1601     ///     let (left, right) = v.split_at_unchecked(2);
1602     ///     assert_eq!(left, [1, 2]);
1603     ///     assert_eq!(right, [3, 4, 5, 6]);
1604     /// }
1605     ///
1606     /// unsafe {
1607     ///     let (left, right) = v.split_at_unchecked(6);
1608     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1609     ///     assert_eq!(right, []);
1610     /// }
1611     /// ```
1612     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1613     #[inline]
1614     pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1615         // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1616         unsafe { (self.get_unchecked(..mid), self.get_unchecked(mid..)) }
1617     }
1618
1619     /// Divides one mutable slice into two at an index, without doing bounds checking.
1620     ///
1621     /// The first will contain all indices from `[0, mid)` (excluding
1622     /// the index `mid` itself) and the second will contain all
1623     /// indices from `[mid, len)` (excluding the index `len` itself).
1624     ///
1625     /// For a safe alternative see [`split_at_mut`].
1626     ///
1627     /// # Safety
1628     ///
1629     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1630     /// even if the resulting reference is not used. The caller has to ensure that
1631     /// `0 <= mid <= self.len()`.
1632     ///
1633     /// [`split_at_mut`]: slice::split_at_mut
1634     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1635     ///
1636     /// # Examples
1637     ///
1638     /// ```
1639     /// #![feature(slice_split_at_unchecked)]
1640     ///
1641     /// let mut v = [1, 0, 3, 0, 5, 6];
1642     /// // scoped to restrict the lifetime of the borrows
1643     /// unsafe {
1644     ///     let (left, right) = v.split_at_mut_unchecked(2);
1645     ///     assert_eq!(left, [1, 0]);
1646     ///     assert_eq!(right, [3, 0, 5, 6]);
1647     ///     left[1] = 2;
1648     ///     right[1] = 4;
1649     /// }
1650     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1651     /// ```
1652     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1653     #[inline]
1654     pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1655         let len = self.len();
1656         let ptr = self.as_mut_ptr();
1657
1658         // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1659         //
1660         // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1661         // is fine.
1662         unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) }
1663     }
1664
1665     /// Returns an iterator over subslices separated by elements that match
1666     /// `pred`. The matched element is not contained in the subslices.
1667     ///
1668     /// # Examples
1669     ///
1670     /// ```
1671     /// let slice = [10, 40, 33, 20];
1672     /// let mut iter = slice.split(|num| num % 3 == 0);
1673     ///
1674     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1675     /// assert_eq!(iter.next().unwrap(), &[20]);
1676     /// assert!(iter.next().is_none());
1677     /// ```
1678     ///
1679     /// If the first element is matched, an empty slice will be the first item
1680     /// returned by the iterator. Similarly, if the last element in the slice
1681     /// is matched, an empty slice will be the last item returned by the
1682     /// iterator:
1683     ///
1684     /// ```
1685     /// let slice = [10, 40, 33];
1686     /// let mut iter = slice.split(|num| num % 3 == 0);
1687     ///
1688     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1689     /// assert_eq!(iter.next().unwrap(), &[]);
1690     /// assert!(iter.next().is_none());
1691     /// ```
1692     ///
1693     /// If two matched elements are directly adjacent, an empty slice will be
1694     /// present between them:
1695     ///
1696     /// ```
1697     /// let slice = [10, 6, 33, 20];
1698     /// let mut iter = slice.split(|num| num % 3 == 0);
1699     ///
1700     /// assert_eq!(iter.next().unwrap(), &[10]);
1701     /// assert_eq!(iter.next().unwrap(), &[]);
1702     /// assert_eq!(iter.next().unwrap(), &[20]);
1703     /// assert!(iter.next().is_none());
1704     /// ```
1705     #[stable(feature = "rust1", since = "1.0.0")]
1706     #[inline]
1707     pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1708     where
1709         F: FnMut(&T) -> bool,
1710     {
1711         Split::new(self, pred)
1712     }
1713
1714     /// Returns an iterator over mutable subslices separated by elements that
1715     /// match `pred`. The matched element is not contained in the subslices.
1716     ///
1717     /// # Examples
1718     ///
1719     /// ```
1720     /// let mut v = [10, 40, 30, 20, 60, 50];
1721     ///
1722     /// for group in v.split_mut(|num| *num % 3 == 0) {
1723     ///     group[0] = 1;
1724     /// }
1725     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1726     /// ```
1727     #[stable(feature = "rust1", since = "1.0.0")]
1728     #[inline]
1729     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1730     where
1731         F: FnMut(&T) -> bool,
1732     {
1733         SplitMut::new(self, pred)
1734     }
1735
1736     /// Returns an iterator over subslices separated by elements that match
1737     /// `pred`. The matched element is contained in the end of the previous
1738     /// subslice as a terminator.
1739     ///
1740     /// # Examples
1741     ///
1742     /// ```
1743     /// let slice = [10, 40, 33, 20];
1744     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1745     ///
1746     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1747     /// assert_eq!(iter.next().unwrap(), &[20]);
1748     /// assert!(iter.next().is_none());
1749     /// ```
1750     ///
1751     /// If the last element of the slice is matched,
1752     /// that element will be considered the terminator of the preceding slice.
1753     /// That slice will be the last item returned by the iterator.
1754     ///
1755     /// ```
1756     /// let slice = [3, 10, 40, 33];
1757     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1758     ///
1759     /// assert_eq!(iter.next().unwrap(), &[3]);
1760     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1761     /// assert!(iter.next().is_none());
1762     /// ```
1763     #[stable(feature = "split_inclusive", since = "1.51.0")]
1764     #[inline]
1765     pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1766     where
1767         F: FnMut(&T) -> bool,
1768     {
1769         SplitInclusive::new(self, pred)
1770     }
1771
1772     /// Returns an iterator over mutable subslices separated by elements that
1773     /// match `pred`. The matched element is contained in the previous
1774     /// subslice as a terminator.
1775     ///
1776     /// # Examples
1777     ///
1778     /// ```
1779     /// let mut v = [10, 40, 30, 20, 60, 50];
1780     ///
1781     /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1782     ///     let terminator_idx = group.len()-1;
1783     ///     group[terminator_idx] = 1;
1784     /// }
1785     /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1786     /// ```
1787     #[stable(feature = "split_inclusive", since = "1.51.0")]
1788     #[inline]
1789     pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1790     where
1791         F: FnMut(&T) -> bool,
1792     {
1793         SplitInclusiveMut::new(self, pred)
1794     }
1795
1796     /// Returns an iterator over subslices separated by elements that match
1797     /// `pred`, starting at the end of the slice and working backwards.
1798     /// The matched element is not contained in the subslices.
1799     ///
1800     /// # Examples
1801     ///
1802     /// ```
1803     /// let slice = [11, 22, 33, 0, 44, 55];
1804     /// let mut iter = slice.rsplit(|num| *num == 0);
1805     ///
1806     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1807     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1808     /// assert_eq!(iter.next(), None);
1809     /// ```
1810     ///
1811     /// As with `split()`, if the first or last element is matched, an empty
1812     /// slice will be the first (or last) item returned by the iterator.
1813     ///
1814     /// ```
1815     /// let v = &[0, 1, 1, 2, 3, 5, 8];
1816     /// let mut it = v.rsplit(|n| *n % 2 == 0);
1817     /// assert_eq!(it.next().unwrap(), &[]);
1818     /// assert_eq!(it.next().unwrap(), &[3, 5]);
1819     /// assert_eq!(it.next().unwrap(), &[1, 1]);
1820     /// assert_eq!(it.next().unwrap(), &[]);
1821     /// assert_eq!(it.next(), None);
1822     /// ```
1823     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1824     #[inline]
1825     pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1826     where
1827         F: FnMut(&T) -> bool,
1828     {
1829         RSplit::new(self, pred)
1830     }
1831
1832     /// Returns an iterator over mutable subslices separated by elements that
1833     /// match `pred`, starting at the end of the slice and working
1834     /// backwards. The matched element is not contained in the subslices.
1835     ///
1836     /// # Examples
1837     ///
1838     /// ```
1839     /// let mut v = [100, 400, 300, 200, 600, 500];
1840     ///
1841     /// let mut count = 0;
1842     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1843     ///     count += 1;
1844     ///     group[0] = count;
1845     /// }
1846     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1847     /// ```
1848     ///
1849     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1850     #[inline]
1851     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1852     where
1853         F: FnMut(&T) -> bool,
1854     {
1855         RSplitMut::new(self, pred)
1856     }
1857
1858     /// Returns an iterator over subslices separated by elements that match
1859     /// `pred`, limited to returning at most `n` items. The matched element is
1860     /// not contained in the subslices.
1861     ///
1862     /// The last element returned, if any, will contain the remainder of the
1863     /// slice.
1864     ///
1865     /// # Examples
1866     ///
1867     /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1868     /// `[20, 60, 50]`):
1869     ///
1870     /// ```
1871     /// let v = [10, 40, 30, 20, 60, 50];
1872     ///
1873     /// for group in v.splitn(2, |num| *num % 3 == 0) {
1874     ///     println!("{:?}", group);
1875     /// }
1876     /// ```
1877     #[stable(feature = "rust1", since = "1.0.0")]
1878     #[inline]
1879     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1880     where
1881         F: FnMut(&T) -> bool,
1882     {
1883         SplitN::new(self.split(pred), n)
1884     }
1885
1886     /// Returns an iterator over subslices separated by elements that match
1887     /// `pred`, limited to returning at most `n` items. The matched element is
1888     /// not contained in the subslices.
1889     ///
1890     /// The last element returned, if any, will contain the remainder of the
1891     /// slice.
1892     ///
1893     /// # Examples
1894     ///
1895     /// ```
1896     /// let mut v = [10, 40, 30, 20, 60, 50];
1897     ///
1898     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1899     ///     group[0] = 1;
1900     /// }
1901     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1902     /// ```
1903     #[stable(feature = "rust1", since = "1.0.0")]
1904     #[inline]
1905     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1906     where
1907         F: FnMut(&T) -> bool,
1908     {
1909         SplitNMut::new(self.split_mut(pred), n)
1910     }
1911
1912     /// Returns an iterator over subslices separated by elements that match
1913     /// `pred` limited to returning at most `n` items. This starts at the end of
1914     /// the slice and works backwards. The matched element is not contained in
1915     /// the subslices.
1916     ///
1917     /// The last element returned, if any, will contain the remainder of the
1918     /// slice.
1919     ///
1920     /// # Examples
1921     ///
1922     /// Print the slice split once, starting from the end, by numbers divisible
1923     /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1924     ///
1925     /// ```
1926     /// let v = [10, 40, 30, 20, 60, 50];
1927     ///
1928     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1929     ///     println!("{:?}", group);
1930     /// }
1931     /// ```
1932     #[stable(feature = "rust1", since = "1.0.0")]
1933     #[inline]
1934     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1935     where
1936         F: FnMut(&T) -> bool,
1937     {
1938         RSplitN::new(self.rsplit(pred), n)
1939     }
1940
1941     /// Returns an iterator over subslices separated by elements that match
1942     /// `pred` limited to returning at most `n` items. This starts at the end of
1943     /// the slice and works backwards. The matched element is not contained in
1944     /// the subslices.
1945     ///
1946     /// The last element returned, if any, will contain the remainder of the
1947     /// slice.
1948     ///
1949     /// # Examples
1950     ///
1951     /// ```
1952     /// let mut s = [10, 40, 30, 20, 60, 50];
1953     ///
1954     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1955     ///     group[0] = 1;
1956     /// }
1957     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1958     /// ```
1959     #[stable(feature = "rust1", since = "1.0.0")]
1960     #[inline]
1961     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1962     where
1963         F: FnMut(&T) -> bool,
1964     {
1965         RSplitNMut::new(self.rsplit_mut(pred), n)
1966     }
1967
1968     /// Returns `true` if the slice contains an element with the given value.
1969     ///
1970     /// # Examples
1971     ///
1972     /// ```
1973     /// let v = [10, 40, 30];
1974     /// assert!(v.contains(&30));
1975     /// assert!(!v.contains(&50));
1976     /// ```
1977     ///
1978     /// If you do not have a `&T`, but some other value that you can compare
1979     /// with one (for example, `String` implements `PartialEq<str>`), you can
1980     /// use `iter().any`:
1981     ///
1982     /// ```
1983     /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1984     /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1985     /// assert!(!v.iter().any(|e| e == "hi"));
1986     /// ```
1987     #[stable(feature = "rust1", since = "1.0.0")]
1988     #[inline]
1989     pub fn contains(&self, x: &T) -> bool
1990     where
1991         T: PartialEq,
1992     {
1993         cmp::SliceContains::slice_contains(x, self)
1994     }
1995
1996     /// Returns `true` if `needle` is a prefix of the slice.
1997     ///
1998     /// # Examples
1999     ///
2000     /// ```
2001     /// let v = [10, 40, 30];
2002     /// assert!(v.starts_with(&[10]));
2003     /// assert!(v.starts_with(&[10, 40]));
2004     /// assert!(!v.starts_with(&[50]));
2005     /// assert!(!v.starts_with(&[10, 50]));
2006     /// ```
2007     ///
2008     /// Always returns `true` if `needle` is an empty slice:
2009     ///
2010     /// ```
2011     /// let v = &[10, 40, 30];
2012     /// assert!(v.starts_with(&[]));
2013     /// let v: &[u8] = &[];
2014     /// assert!(v.starts_with(&[]));
2015     /// ```
2016     #[stable(feature = "rust1", since = "1.0.0")]
2017     pub fn starts_with(&self, needle: &[T]) -> bool
2018     where
2019         T: PartialEq,
2020     {
2021         let n = needle.len();
2022         self.len() >= n && needle == &self[..n]
2023     }
2024
2025     /// Returns `true` if `needle` is a suffix of the slice.
2026     ///
2027     /// # Examples
2028     ///
2029     /// ```
2030     /// let v = [10, 40, 30];
2031     /// assert!(v.ends_with(&[30]));
2032     /// assert!(v.ends_with(&[40, 30]));
2033     /// assert!(!v.ends_with(&[50]));
2034     /// assert!(!v.ends_with(&[50, 30]));
2035     /// ```
2036     ///
2037     /// Always returns `true` if `needle` is an empty slice:
2038     ///
2039     /// ```
2040     /// let v = &[10, 40, 30];
2041     /// assert!(v.ends_with(&[]));
2042     /// let v: &[u8] = &[];
2043     /// assert!(v.ends_with(&[]));
2044     /// ```
2045     #[stable(feature = "rust1", since = "1.0.0")]
2046     pub fn ends_with(&self, needle: &[T]) -> bool
2047     where
2048         T: PartialEq,
2049     {
2050         let (m, n) = (self.len(), needle.len());
2051         m >= n && needle == &self[m - n..]
2052     }
2053
2054     /// Returns a subslice with the prefix removed.
2055     ///
2056     /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2057     /// If `prefix` is empty, simply returns the original slice.
2058     ///
2059     /// If the slice does not start with `prefix`, returns `None`.
2060     ///
2061     /// # Examples
2062     ///
2063     /// ```
2064     /// let v = &[10, 40, 30];
2065     /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2066     /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2067     /// assert_eq!(v.strip_prefix(&[50]), None);
2068     /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2069     ///
2070     /// let prefix : &str = "he";
2071     /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2072     ///            Some(b"llo".as_ref()));
2073     /// ```
2074     #[must_use = "returns the subslice without modifying the original"]
2075     #[stable(feature = "slice_strip", since = "1.51.0")]
2076     pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2077     where
2078         T: PartialEq,
2079     {
2080         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2081         let prefix = prefix.as_slice();
2082         let n = prefix.len();
2083         if n <= self.len() {
2084             let (head, tail) = self.split_at(n);
2085             if head == prefix {
2086                 return Some(tail);
2087             }
2088         }
2089         None
2090     }
2091
2092     /// Returns a subslice with the suffix removed.
2093     ///
2094     /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2095     /// If `suffix` is empty, simply returns the original slice.
2096     ///
2097     /// If the slice does not end with `suffix`, returns `None`.
2098     ///
2099     /// # Examples
2100     ///
2101     /// ```
2102     /// let v = &[10, 40, 30];
2103     /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2104     /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2105     /// assert_eq!(v.strip_suffix(&[50]), None);
2106     /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2107     /// ```
2108     #[must_use = "returns the subslice without modifying the original"]
2109     #[stable(feature = "slice_strip", since = "1.51.0")]
2110     pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2111     where
2112         T: PartialEq,
2113     {
2114         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2115         let suffix = suffix.as_slice();
2116         let (len, n) = (self.len(), suffix.len());
2117         if n <= len {
2118             let (head, tail) = self.split_at(len - n);
2119             if tail == suffix {
2120                 return Some(head);
2121             }
2122         }
2123         None
2124     }
2125
2126     /// Binary searches this sorted slice for a given element.
2127     ///
2128     /// If the value is found then [`Result::Ok`] is returned, containing the
2129     /// index of the matching element. If there are multiple matches, then any
2130     /// one of the matches could be returned. The index is chosen
2131     /// deterministically, but is subject to change in future versions of Rust.
2132     /// If the value is not found then [`Result::Err`] is returned, containing
2133     /// the index where a matching element could be inserted while maintaining
2134     /// sorted order.
2135     ///
2136     /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2137     ///
2138     /// [`binary_search_by`]: slice::binary_search_by
2139     /// [`binary_search_by_key`]: slice::binary_search_by_key
2140     /// [`partition_point`]: slice::partition_point
2141     ///
2142     /// # Examples
2143     ///
2144     /// Looks up a series of four elements. The first is found, with a
2145     /// uniquely determined position; the second and third are not
2146     /// found; the fourth could match any position in `[1, 4]`.
2147     ///
2148     /// ```
2149     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2150     ///
2151     /// assert_eq!(s.binary_search(&13),  Ok(9));
2152     /// assert_eq!(s.binary_search(&4),   Err(7));
2153     /// assert_eq!(s.binary_search(&100), Err(13));
2154     /// let r = s.binary_search(&1);
2155     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2156     /// ```
2157     ///
2158     /// If you want to insert an item to a sorted vector, while maintaining
2159     /// sort order:
2160     ///
2161     /// ```
2162     /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2163     /// let num = 42;
2164     /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
2165     /// s.insert(idx, num);
2166     /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2167     /// ```
2168     #[stable(feature = "rust1", since = "1.0.0")]
2169     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2170     where
2171         T: Ord,
2172     {
2173         self.binary_search_by(|p| p.cmp(x))
2174     }
2175
2176     /// Binary searches this sorted slice with a comparator function.
2177     ///
2178     /// The comparator function should implement an order consistent
2179     /// with the sort order of the underlying slice, returning an
2180     /// order code that indicates whether its argument is `Less`,
2181     /// `Equal` or `Greater` the desired target.
2182     ///
2183     /// If the value is found then [`Result::Ok`] is returned, containing the
2184     /// index of the matching element. If there are multiple matches, then any
2185     /// one of the matches could be returned. The index is chosen
2186     /// deterministically, but is subject to change in future versions of Rust.
2187     /// If the value is not found then [`Result::Err`] is returned, containing
2188     /// the index where a matching element could be inserted while maintaining
2189     /// sorted order.
2190     ///
2191     /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2192     ///
2193     /// [`binary_search`]: slice::binary_search
2194     /// [`binary_search_by_key`]: slice::binary_search_by_key
2195     /// [`partition_point`]: slice::partition_point
2196     ///
2197     /// # Examples
2198     ///
2199     /// Looks up a series of four elements. The first is found, with a
2200     /// uniquely determined position; the second and third are not
2201     /// found; the fourth could match any position in `[1, 4]`.
2202     ///
2203     /// ```
2204     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2205     ///
2206     /// let seek = 13;
2207     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2208     /// let seek = 4;
2209     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2210     /// let seek = 100;
2211     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2212     /// let seek = 1;
2213     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2214     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2215     /// ```
2216     #[stable(feature = "rust1", since = "1.0.0")]
2217     #[inline]
2218     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2219     where
2220         F: FnMut(&'a T) -> Ordering,
2221     {
2222         let mut size = self.len();
2223         let mut left = 0;
2224         let mut right = size;
2225         while left < right {
2226             let mid = left + size / 2;
2227
2228             // SAFETY: the call is made safe by the following invariants:
2229             // - `mid >= 0`
2230             // - `mid < size`: `mid` is limited by `[left; right)` bound.
2231             let cmp = f(unsafe { self.get_unchecked(mid) });
2232
2233             // The reason why we use if/else control flow rather than match
2234             // is because match reorders comparison operations, which is perf sensitive.
2235             // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra.
2236             if cmp == Less {
2237                 left = mid + 1;
2238             } else if cmp == Greater {
2239                 right = mid;
2240             } else {
2241                 // SAFETY: same as the `get_unchecked` above
2242                 unsafe { crate::intrinsics::assume(mid < self.len()) };
2243                 return Ok(mid);
2244             }
2245
2246             size = right - left;
2247         }
2248         Err(left)
2249     }
2250
2251     /// Binary searches this sorted slice with a key extraction function.
2252     ///
2253     /// Assumes that the slice is sorted by the key, for instance with
2254     /// [`sort_by_key`] using the same key extraction function.
2255     ///
2256     /// If the value is found then [`Result::Ok`] is returned, containing the
2257     /// index of the matching element. If there are multiple matches, then any
2258     /// one of the matches could be returned. The index is chosen
2259     /// deterministically, but is subject to change in future versions of Rust.
2260     /// If the value is not found then [`Result::Err`] is returned, containing
2261     /// the index where a matching element could be inserted while maintaining
2262     /// sorted order.
2263     ///
2264     /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2265     ///
2266     /// [`sort_by_key`]: slice::sort_by_key
2267     /// [`binary_search`]: slice::binary_search
2268     /// [`binary_search_by`]: slice::binary_search_by
2269     /// [`partition_point`]: slice::partition_point
2270     ///
2271     /// # Examples
2272     ///
2273     /// Looks up a series of four elements in a slice of pairs sorted by
2274     /// their second elements. The first is found, with a uniquely
2275     /// determined position; the second and third are not found; the
2276     /// fourth could match any position in `[1, 4]`.
2277     ///
2278     /// ```
2279     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2280     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2281     ///          (1, 21), (2, 34), (4, 55)];
2282     ///
2283     /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
2284     /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
2285     /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2286     /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2287     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2288     /// ```
2289     // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2290     // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
2291     // This breaks links when slice is displayed in core, but changing it to use relative links
2292     // would break when the item is re-exported. So allow the core links to be broken for now.
2293     #[allow(rustdoc::broken_intra_doc_links)]
2294     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2295     #[inline]
2296     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2297     where
2298         F: FnMut(&'a T) -> B,
2299         B: Ord,
2300     {
2301         self.binary_search_by(|k| f(k).cmp(b))
2302     }
2303
2304     /// Sorts the slice, but might not preserve the order of equal elements.
2305     ///
2306     /// This sort is unstable (i.e., may reorder equal elements), in-place
2307     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2308     ///
2309     /// # Current implementation
2310     ///
2311     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2312     /// which combines the fast average case of randomized quicksort with the fast worst case of
2313     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2314     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2315     /// deterministic behavior.
2316     ///
2317     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2318     /// slice consists of several concatenated sorted sequences.
2319     ///
2320     /// # Examples
2321     ///
2322     /// ```
2323     /// let mut v = [-5, 4, 1, -3, 2];
2324     ///
2325     /// v.sort_unstable();
2326     /// assert!(v == [-5, -3, 1, 2, 4]);
2327     /// ```
2328     ///
2329     /// [pdqsort]: https://github.com/orlp/pdqsort
2330     #[stable(feature = "sort_unstable", since = "1.20.0")]
2331     #[inline]
2332     pub fn sort_unstable(&mut self)
2333     where
2334         T: Ord,
2335     {
2336         sort::quicksort(self, |a, b| a.lt(b));
2337     }
2338
2339     /// Sorts the slice with a comparator function, but might not preserve the order of equal
2340     /// elements.
2341     ///
2342     /// This sort is unstable (i.e., may reorder equal elements), in-place
2343     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2344     ///
2345     /// The comparator function must define a total ordering for the elements in the slice. If
2346     /// the ordering is not total, the order of the elements is unspecified. An order is a
2347     /// total order if it is (for all `a`, `b` and `c`):
2348     ///
2349     /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
2350     /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
2351     ///
2352     /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2353     /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2354     ///
2355     /// ```
2356     /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2357     /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2358     /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2359     /// ```
2360     ///
2361     /// # Current implementation
2362     ///
2363     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2364     /// which combines the fast average case of randomized quicksort with the fast worst case of
2365     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2366     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2367     /// deterministic behavior.
2368     ///
2369     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2370     /// slice consists of several concatenated sorted sequences.
2371     ///
2372     /// # Examples
2373     ///
2374     /// ```
2375     /// let mut v = [5, 4, 1, 3, 2];
2376     /// v.sort_unstable_by(|a, b| a.cmp(b));
2377     /// assert!(v == [1, 2, 3, 4, 5]);
2378     ///
2379     /// // reverse sorting
2380     /// v.sort_unstable_by(|a, b| b.cmp(a));
2381     /// assert!(v == [5, 4, 3, 2, 1]);
2382     /// ```
2383     ///
2384     /// [pdqsort]: https://github.com/orlp/pdqsort
2385     #[stable(feature = "sort_unstable", since = "1.20.0")]
2386     #[inline]
2387     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2388     where
2389         F: FnMut(&T, &T) -> Ordering,
2390     {
2391         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2392     }
2393
2394     /// Sorts the slice with a key extraction function, but might not preserve the order of equal
2395     /// elements.
2396     ///
2397     /// This sort is unstable (i.e., may reorder equal elements), in-place
2398     /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2399     /// *O*(*m*).
2400     ///
2401     /// # Current implementation
2402     ///
2403     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2404     /// which combines the fast average case of randomized quicksort with the fast worst case of
2405     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2406     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2407     /// deterministic behavior.
2408     ///
2409     /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2410     /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2411     /// cases where the key function is expensive.
2412     ///
2413     /// # Examples
2414     ///
2415     /// ```
2416     /// let mut v = [-5i32, 4, 1, -3, 2];
2417     ///
2418     /// v.sort_unstable_by_key(|k| k.abs());
2419     /// assert!(v == [1, 2, -3, 4, -5]);
2420     /// ```
2421     ///
2422     /// [pdqsort]: https://github.com/orlp/pdqsort
2423     #[stable(feature = "sort_unstable", since = "1.20.0")]
2424     #[inline]
2425     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2426     where
2427         F: FnMut(&T) -> K,
2428         K: Ord,
2429     {
2430         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2431     }
2432
2433     /// Reorder the slice such that the element at `index` is at its final sorted position.
2434     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2435     #[rustc_deprecated(since = "1.49.0", reason = "use the select_nth_unstable() instead")]
2436     #[inline]
2437     pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2438     where
2439         T: Ord,
2440     {
2441         self.select_nth_unstable(index)
2442     }
2443
2444     /// Reorder the slice with a comparator function such that the element at `index` is at its
2445     /// final sorted position.
2446     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2447     #[rustc_deprecated(since = "1.49.0", reason = "use select_nth_unstable_by() instead")]
2448     #[inline]
2449     pub fn partition_at_index_by<F>(
2450         &mut self,
2451         index: usize,
2452         compare: F,
2453     ) -> (&mut [T], &mut T, &mut [T])
2454     where
2455         F: FnMut(&T, &T) -> Ordering,
2456     {
2457         self.select_nth_unstable_by(index, compare)
2458     }
2459
2460     /// Reorder the slice with a key extraction function such that the element at `index` is at its
2461     /// final sorted position.
2462     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2463     #[rustc_deprecated(since = "1.49.0", reason = "use the select_nth_unstable_by_key() instead")]
2464     #[inline]
2465     pub fn partition_at_index_by_key<K, F>(
2466         &mut self,
2467         index: usize,
2468         f: F,
2469     ) -> (&mut [T], &mut T, &mut [T])
2470     where
2471         F: FnMut(&T) -> K,
2472         K: Ord,
2473     {
2474         self.select_nth_unstable_by_key(index, f)
2475     }
2476
2477     /// Reorder the slice such that the element at `index` is at its final sorted position.
2478     ///
2479     /// This reordering has the additional property that any value at position `i < index` will be
2480     /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2481     /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2482     /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2483     /// element" in other libraries. It returns a triplet of the following values: all elements less
2484     /// than the one at the given index, the value at the given index, and all elements greater than
2485     /// the one at the given index.
2486     ///
2487     /// # Current implementation
2488     ///
2489     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2490     /// used for [`sort_unstable`].
2491     ///
2492     /// [`sort_unstable`]: slice::sort_unstable
2493     ///
2494     /// # Panics
2495     ///
2496     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2497     ///
2498     /// # Examples
2499     ///
2500     /// ```
2501     /// let mut v = [-5i32, 4, 1, -3, 2];
2502     ///
2503     /// // Find the median
2504     /// v.select_nth_unstable(2);
2505     ///
2506     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2507     /// // about the specified index.
2508     /// assert!(v == [-3, -5, 1, 2, 4] ||
2509     ///         v == [-5, -3, 1, 2, 4] ||
2510     ///         v == [-3, -5, 1, 4, 2] ||
2511     ///         v == [-5, -3, 1, 4, 2]);
2512     /// ```
2513     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2514     #[inline]
2515     pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2516     where
2517         T: Ord,
2518     {
2519         let mut f = |a: &T, b: &T| a.lt(b);
2520         sort::partition_at_index(self, index, &mut f)
2521     }
2522
2523     /// Reorder the slice with a comparator function such that the element at `index` is at its
2524     /// final sorted position.
2525     ///
2526     /// This reordering has the additional property that any value at position `i < index` will be
2527     /// less than or equal to any value at a position `j > index` using the comparator function.
2528     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2529     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2530     /// is also known as "kth element" in other libraries. It returns a triplet of the following
2531     /// values: all elements less than the one at the given index, the value at the given index,
2532     /// and all elements greater than the one at the given index, using the provided comparator
2533     /// function.
2534     ///
2535     /// # Current implementation
2536     ///
2537     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2538     /// used for [`sort_unstable`].
2539     ///
2540     /// [`sort_unstable`]: slice::sort_unstable
2541     ///
2542     /// # Panics
2543     ///
2544     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2545     ///
2546     /// # Examples
2547     ///
2548     /// ```
2549     /// let mut v = [-5i32, 4, 1, -3, 2];
2550     ///
2551     /// // Find the median as if the slice were sorted in descending order.
2552     /// v.select_nth_unstable_by(2, |a, b| b.cmp(a));
2553     ///
2554     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2555     /// // about the specified index.
2556     /// assert!(v == [2, 4, 1, -5, -3] ||
2557     ///         v == [2, 4, 1, -3, -5] ||
2558     ///         v == [4, 2, 1, -5, -3] ||
2559     ///         v == [4, 2, 1, -3, -5]);
2560     /// ```
2561     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2562     #[inline]
2563     pub fn select_nth_unstable_by<F>(
2564         &mut self,
2565         index: usize,
2566         mut compare: F,
2567     ) -> (&mut [T], &mut T, &mut [T])
2568     where
2569         F: FnMut(&T, &T) -> Ordering,
2570     {
2571         let mut f = |a: &T, b: &T| compare(a, b) == Less;
2572         sort::partition_at_index(self, index, &mut f)
2573     }
2574
2575     /// Reorder the slice with a key extraction function such that the element at `index` is at its
2576     /// final sorted position.
2577     ///
2578     /// This reordering has the additional property that any value at position `i < index` will be
2579     /// less than or equal to any value at a position `j > index` using the key extraction function.
2580     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2581     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2582     /// is also known as "kth element" in other libraries. It returns a triplet of the following
2583     /// values: all elements less than the one at the given index, the value at the given index, and
2584     /// all elements greater than the one at the given index, using the provided key extraction
2585     /// function.
2586     ///
2587     /// # Current implementation
2588     ///
2589     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2590     /// used for [`sort_unstable`].
2591     ///
2592     /// [`sort_unstable`]: slice::sort_unstable
2593     ///
2594     /// # Panics
2595     ///
2596     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2597     ///
2598     /// # Examples
2599     ///
2600     /// ```
2601     /// let mut v = [-5i32, 4, 1, -3, 2];
2602     ///
2603     /// // Return the median as if the array were sorted according to absolute value.
2604     /// v.select_nth_unstable_by_key(2, |a| a.abs());
2605     ///
2606     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2607     /// // about the specified index.
2608     /// assert!(v == [1, 2, -3, 4, -5] ||
2609     ///         v == [1, 2, -3, -5, 4] ||
2610     ///         v == [2, 1, -3, 4, -5] ||
2611     ///         v == [2, 1, -3, -5, 4]);
2612     /// ```
2613     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2614     #[inline]
2615     pub fn select_nth_unstable_by_key<K, F>(
2616         &mut self,
2617         index: usize,
2618         mut f: F,
2619     ) -> (&mut [T], &mut T, &mut [T])
2620     where
2621         F: FnMut(&T) -> K,
2622         K: Ord,
2623     {
2624         let mut g = |a: &T, b: &T| f(a).lt(&f(b));
2625         sort::partition_at_index(self, index, &mut g)
2626     }
2627
2628     /// Moves all consecutive repeated elements to the end of the slice according to the
2629     /// [`PartialEq`] trait implementation.
2630     ///
2631     /// Returns two slices. The first contains no consecutive repeated elements.
2632     /// The second contains all the duplicates in no specified order.
2633     ///
2634     /// If the slice is sorted, the first returned slice contains no duplicates.
2635     ///
2636     /// # Examples
2637     ///
2638     /// ```
2639     /// #![feature(slice_partition_dedup)]
2640     ///
2641     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2642     ///
2643     /// let (dedup, duplicates) = slice.partition_dedup();
2644     ///
2645     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2646     /// assert_eq!(duplicates, [2, 3, 1]);
2647     /// ```
2648     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2649     #[inline]
2650     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2651     where
2652         T: PartialEq,
2653     {
2654         self.partition_dedup_by(|a, b| a == b)
2655     }
2656
2657     /// Moves all but the first of consecutive elements to the end of the slice satisfying
2658     /// a given equality relation.
2659     ///
2660     /// Returns two slices. The first contains no consecutive repeated elements.
2661     /// The second contains all the duplicates in no specified order.
2662     ///
2663     /// The `same_bucket` function is passed references to two elements from the slice and
2664     /// must determine if the elements compare equal. The elements are passed in opposite order
2665     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2666     /// at the end of the slice.
2667     ///
2668     /// If the slice is sorted, the first returned slice contains no duplicates.
2669     ///
2670     /// # Examples
2671     ///
2672     /// ```
2673     /// #![feature(slice_partition_dedup)]
2674     ///
2675     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2676     ///
2677     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2678     ///
2679     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2680     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2681     /// ```
2682     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2683     #[inline]
2684     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2685     where
2686         F: FnMut(&mut T, &mut T) -> bool,
2687     {
2688         // Although we have a mutable reference to `self`, we cannot make
2689         // *arbitrary* changes. The `same_bucket` calls could panic, so we
2690         // must ensure that the slice is in a valid state at all times.
2691         //
2692         // The way that we handle this is by using swaps; we iterate
2693         // over all the elements, swapping as we go so that at the end
2694         // the elements we wish to keep are in the front, and those we
2695         // wish to reject are at the back. We can then split the slice.
2696         // This operation is still `O(n)`.
2697         //
2698         // Example: We start in this state, where `r` represents "next
2699         // read" and `w` represents "next_write`.
2700         //
2701         //           r
2702         //     +---+---+---+---+---+---+
2703         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2704         //     +---+---+---+---+---+---+
2705         //           w
2706         //
2707         // Comparing self[r] against self[w-1], this is not a duplicate, so
2708         // we swap self[r] and self[w] (no effect as r==w) and then increment both
2709         // r and w, leaving us with:
2710         //
2711         //               r
2712         //     +---+---+---+---+---+---+
2713         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2714         //     +---+---+---+---+---+---+
2715         //               w
2716         //
2717         // Comparing self[r] against self[w-1], this value is a duplicate,
2718         // so we increment `r` but leave everything else unchanged:
2719         //
2720         //                   r
2721         //     +---+---+---+---+---+---+
2722         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2723         //     +---+---+---+---+---+---+
2724         //               w
2725         //
2726         // Comparing self[r] against self[w-1], this is not a duplicate,
2727         // so swap self[r] and self[w] and advance r and w:
2728         //
2729         //                       r
2730         //     +---+---+---+---+---+---+
2731         //     | 0 | 1 | 2 | 1 | 3 | 3 |
2732         //     +---+---+---+---+---+---+
2733         //                   w
2734         //
2735         // Not a duplicate, repeat:
2736         //
2737         //                           r
2738         //     +---+---+---+---+---+---+
2739         //     | 0 | 1 | 2 | 3 | 1 | 3 |
2740         //     +---+---+---+---+---+---+
2741         //                       w
2742         //
2743         // Duplicate, advance r. End of slice. Split at w.
2744
2745         let len = self.len();
2746         if len <= 1 {
2747             return (self, &mut []);
2748         }
2749
2750         let ptr = self.as_mut_ptr();
2751         let mut next_read: usize = 1;
2752         let mut next_write: usize = 1;
2753
2754         // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2755         // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2756         // one element before `ptr_write`, but `next_write` starts at 1, so
2757         // `prev_ptr_write` is never less than 0 and is inside the slice.
2758         // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2759         // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2760         // and `prev_ptr_write.offset(1)`.
2761         //
2762         // `next_write` is also incremented at most once per loop at most meaning
2763         // no element is skipped when it may need to be swapped.
2764         //
2765         // `ptr_read` and `prev_ptr_write` never point to the same element. This
2766         // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2767         // The explanation is simply that `next_read >= next_write` is always true,
2768         // thus `next_read > next_write - 1` is too.
2769         unsafe {
2770             // Avoid bounds checks by using raw pointers.
2771             while next_read < len {
2772                 let ptr_read = ptr.add(next_read);
2773                 let prev_ptr_write = ptr.add(next_write - 1);
2774                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2775                     if next_read != next_write {
2776                         let ptr_write = prev_ptr_write.offset(1);
2777                         mem::swap(&mut *ptr_read, &mut *ptr_write);
2778                     }
2779                     next_write += 1;
2780                 }
2781                 next_read += 1;
2782             }
2783         }
2784
2785         self.split_at_mut(next_write)
2786     }
2787
2788     /// Moves all but the first of consecutive elements to the end of the slice that resolve
2789     /// to the same key.
2790     ///
2791     /// Returns two slices. The first contains no consecutive repeated elements.
2792     /// The second contains all the duplicates in no specified order.
2793     ///
2794     /// If the slice is sorted, the first returned slice contains no duplicates.
2795     ///
2796     /// # Examples
2797     ///
2798     /// ```
2799     /// #![feature(slice_partition_dedup)]
2800     ///
2801     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2802     ///
2803     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2804     ///
2805     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2806     /// assert_eq!(duplicates, [21, 30, 13]);
2807     /// ```
2808     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2809     #[inline]
2810     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2811     where
2812         F: FnMut(&mut T) -> K,
2813         K: PartialEq,
2814     {
2815         self.partition_dedup_by(|a, b| key(a) == key(b))
2816     }
2817
2818     /// Rotates the slice in-place such that the first `mid` elements of the
2819     /// slice move to the end while the last `self.len() - mid` elements move to
2820     /// the front. After calling `rotate_left`, the element previously at index
2821     /// `mid` will become the first element in the slice.
2822     ///
2823     /// # Panics
2824     ///
2825     /// This function will panic if `mid` is greater than the length of the
2826     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2827     /// rotation.
2828     ///
2829     /// # Complexity
2830     ///
2831     /// Takes linear (in `self.len()`) time.
2832     ///
2833     /// # Examples
2834     ///
2835     /// ```
2836     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2837     /// a.rotate_left(2);
2838     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2839     /// ```
2840     ///
2841     /// Rotating a subslice:
2842     ///
2843     /// ```
2844     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2845     /// a[1..5].rotate_left(1);
2846     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2847     /// ```
2848     #[stable(feature = "slice_rotate", since = "1.26.0")]
2849     pub fn rotate_left(&mut self, mid: usize) {
2850         assert!(mid <= self.len());
2851         let k = self.len() - mid;
2852         let p = self.as_mut_ptr();
2853
2854         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2855         // valid for reading and writing, as required by `ptr_rotate`.
2856         unsafe {
2857             rotate::ptr_rotate(mid, p.add(mid), k);
2858         }
2859     }
2860
2861     /// Rotates the slice in-place such that the first `self.len() - k`
2862     /// elements of the slice move to the end while the last `k` elements move
2863     /// to the front. After calling `rotate_right`, the element previously at
2864     /// index `self.len() - k` will become the first element in the slice.
2865     ///
2866     /// # Panics
2867     ///
2868     /// This function will panic if `k` is greater than the length of the
2869     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2870     /// rotation.
2871     ///
2872     /// # Complexity
2873     ///
2874     /// Takes linear (in `self.len()`) time.
2875     ///
2876     /// # Examples
2877     ///
2878     /// ```
2879     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2880     /// a.rotate_right(2);
2881     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2882     /// ```
2883     ///
2884     /// Rotate a subslice:
2885     ///
2886     /// ```
2887     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2888     /// a[1..5].rotate_right(1);
2889     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2890     /// ```
2891     #[stable(feature = "slice_rotate", since = "1.26.0")]
2892     pub fn rotate_right(&mut self, k: usize) {
2893         assert!(k <= self.len());
2894         let mid = self.len() - k;
2895         let p = self.as_mut_ptr();
2896
2897         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2898         // valid for reading and writing, as required by `ptr_rotate`.
2899         unsafe {
2900             rotate::ptr_rotate(mid, p.add(mid), k);
2901         }
2902     }
2903
2904     /// Fills `self` with elements by cloning `value`.
2905     ///
2906     /// # Examples
2907     ///
2908     /// ```
2909     /// let mut buf = vec![0; 10];
2910     /// buf.fill(1);
2911     /// assert_eq!(buf, vec![1; 10]);
2912     /// ```
2913     #[doc(alias = "memset")]
2914     #[stable(feature = "slice_fill", since = "1.50.0")]
2915     pub fn fill(&mut self, value: T)
2916     where
2917         T: Clone,
2918     {
2919         specialize::SpecFill::spec_fill(self, value);
2920     }
2921
2922     /// Fills `self` with elements returned by calling a closure repeatedly.
2923     ///
2924     /// This method uses a closure to create new values. If you'd rather
2925     /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
2926     /// trait to generate values, you can pass [`Default::default`] as the
2927     /// argument.
2928     ///
2929     /// [`fill`]: slice::fill
2930     ///
2931     /// # Examples
2932     ///
2933     /// ```
2934     /// let mut buf = vec![1; 10];
2935     /// buf.fill_with(Default::default);
2936     /// assert_eq!(buf, vec![0; 10]);
2937     /// ```
2938     #[doc(alias = "memset")]
2939     #[stable(feature = "slice_fill_with", since = "1.51.0")]
2940     pub fn fill_with<F>(&mut self, mut f: F)
2941     where
2942         F: FnMut() -> T,
2943     {
2944         for el in self {
2945             *el = f();
2946         }
2947     }
2948
2949     /// Copies the elements from `src` into `self`.
2950     ///
2951     /// The length of `src` must be the same as `self`.
2952     ///
2953     /// If `T` implements `Copy`, it can be more performant to use
2954     /// [`copy_from_slice`].
2955     ///
2956     /// # Panics
2957     ///
2958     /// This function will panic if the two slices have different lengths.
2959     ///
2960     /// # Examples
2961     ///
2962     /// Cloning two elements from a slice into another:
2963     ///
2964     /// ```
2965     /// let src = [1, 2, 3, 4];
2966     /// let mut dst = [0, 0];
2967     ///
2968     /// // Because the slices have to be the same length,
2969     /// // we slice the source slice from four elements
2970     /// // to two. It will panic if we don't do this.
2971     /// dst.clone_from_slice(&src[2..]);
2972     ///
2973     /// assert_eq!(src, [1, 2, 3, 4]);
2974     /// assert_eq!(dst, [3, 4]);
2975     /// ```
2976     ///
2977     /// Rust enforces that there can only be one mutable reference with no
2978     /// immutable references to a particular piece of data in a particular
2979     /// scope. Because of this, attempting to use `clone_from_slice` on a
2980     /// single slice will result in a compile failure:
2981     ///
2982     /// ```compile_fail
2983     /// let mut slice = [1, 2, 3, 4, 5];
2984     ///
2985     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2986     /// ```
2987     ///
2988     /// To work around this, we can use [`split_at_mut`] to create two distinct
2989     /// sub-slices from a slice:
2990     ///
2991     /// ```
2992     /// let mut slice = [1, 2, 3, 4, 5];
2993     ///
2994     /// {
2995     ///     let (left, right) = slice.split_at_mut(2);
2996     ///     left.clone_from_slice(&right[1..]);
2997     /// }
2998     ///
2999     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3000     /// ```
3001     ///
3002     /// [`copy_from_slice`]: slice::copy_from_slice
3003     /// [`split_at_mut`]: slice::split_at_mut
3004     #[stable(feature = "clone_from_slice", since = "1.7.0")]
3005     pub fn clone_from_slice(&mut self, src: &[T])
3006     where
3007         T: Clone,
3008     {
3009         self.spec_clone_from(src);
3010     }
3011
3012     /// Copies all elements from `src` into `self`, using a memcpy.
3013     ///
3014     /// The length of `src` must be the same as `self`.
3015     ///
3016     /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3017     ///
3018     /// # Panics
3019     ///
3020     /// This function will panic if the two slices have different lengths.
3021     ///
3022     /// # Examples
3023     ///
3024     /// Copying two elements from a slice into another:
3025     ///
3026     /// ```
3027     /// let src = [1, 2, 3, 4];
3028     /// let mut dst = [0, 0];
3029     ///
3030     /// // Because the slices have to be the same length,
3031     /// // we slice the source slice from four elements
3032     /// // to two. It will panic if we don't do this.
3033     /// dst.copy_from_slice(&src[2..]);
3034     ///
3035     /// assert_eq!(src, [1, 2, 3, 4]);
3036     /// assert_eq!(dst, [3, 4]);
3037     /// ```
3038     ///
3039     /// Rust enforces that there can only be one mutable reference with no
3040     /// immutable references to a particular piece of data in a particular
3041     /// scope. Because of this, attempting to use `copy_from_slice` on a
3042     /// single slice will result in a compile failure:
3043     ///
3044     /// ```compile_fail
3045     /// let mut slice = [1, 2, 3, 4, 5];
3046     ///
3047     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3048     /// ```
3049     ///
3050     /// To work around this, we can use [`split_at_mut`] to create two distinct
3051     /// sub-slices from a slice:
3052     ///
3053     /// ```
3054     /// let mut slice = [1, 2, 3, 4, 5];
3055     ///
3056     /// {
3057     ///     let (left, right) = slice.split_at_mut(2);
3058     ///     left.copy_from_slice(&right[1..]);
3059     /// }
3060     ///
3061     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3062     /// ```
3063     ///
3064     /// [`clone_from_slice`]: slice::clone_from_slice
3065     /// [`split_at_mut`]: slice::split_at_mut
3066     #[doc(alias = "memcpy")]
3067     #[stable(feature = "copy_from_slice", since = "1.9.0")]
3068     pub fn copy_from_slice(&mut self, src: &[T])
3069     where
3070         T: Copy,
3071     {
3072         // The panic code path was put into a cold function to not bloat the
3073         // call site.
3074         #[inline(never)]
3075         #[cold]
3076         #[track_caller]
3077         fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3078             panic!(
3079                 "source slice length ({}) does not match destination slice length ({})",
3080                 src_len, dst_len,
3081             );
3082         }
3083
3084         if self.len() != src.len() {
3085             len_mismatch_fail(self.len(), src.len());
3086         }
3087
3088         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3089         // checked to have the same length. The slices cannot overlap because
3090         // mutable references are exclusive.
3091         unsafe {
3092             ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3093         }
3094     }
3095
3096     /// Copies elements from one part of the slice to another part of itself,
3097     /// using a memmove.
3098     ///
3099     /// `src` is the range within `self` to copy from. `dest` is the starting
3100     /// index of the range within `self` to copy to, which will have the same
3101     /// length as `src`. The two ranges may overlap. The ends of the two ranges
3102     /// must be less than or equal to `self.len()`.
3103     ///
3104     /// # Panics
3105     ///
3106     /// This function will panic if either range exceeds the end of the slice,
3107     /// or if the end of `src` is before the start.
3108     ///
3109     /// # Examples
3110     ///
3111     /// Copying four bytes within a slice:
3112     ///
3113     /// ```
3114     /// let mut bytes = *b"Hello, World!";
3115     ///
3116     /// bytes.copy_within(1..5, 8);
3117     ///
3118     /// assert_eq!(&bytes, b"Hello, Wello!");
3119     /// ```
3120     #[stable(feature = "copy_within", since = "1.37.0")]
3121     #[track_caller]
3122     pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3123     where
3124         T: Copy,
3125     {
3126         let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3127         let count = src_end - src_start;
3128         assert!(dest <= self.len() - count, "dest is out of bounds");
3129         // SAFETY: the conditions for `ptr::copy` have all been checked above,
3130         // as have those for `ptr::add`.
3131         unsafe {
3132             // Derive both `src_ptr` and `dest_ptr` from the same loan
3133             let ptr = self.as_mut_ptr();
3134             let src_ptr = ptr.add(src_start);
3135             let dest_ptr = ptr.add(dest);
3136             ptr::copy(src_ptr, dest_ptr, count);
3137         }
3138     }
3139
3140     /// Swaps all elements in `self` with those in `other`.
3141     ///
3142     /// The length of `other` must be the same as `self`.
3143     ///
3144     /// # Panics
3145     ///
3146     /// This function will panic if the two slices have different lengths.
3147     ///
3148     /// # Example
3149     ///
3150     /// Swapping two elements across slices:
3151     ///
3152     /// ```
3153     /// let mut slice1 = [0, 0];
3154     /// let mut slice2 = [1, 2, 3, 4];
3155     ///
3156     /// slice1.swap_with_slice(&mut slice2[2..]);
3157     ///
3158     /// assert_eq!(slice1, [3, 4]);
3159     /// assert_eq!(slice2, [1, 2, 0, 0]);
3160     /// ```
3161     ///
3162     /// Rust enforces that there can only be one mutable reference to a
3163     /// particular piece of data in a particular scope. Because of this,
3164     /// attempting to use `swap_with_slice` on a single slice will result in
3165     /// a compile failure:
3166     ///
3167     /// ```compile_fail
3168     /// let mut slice = [1, 2, 3, 4, 5];
3169     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3170     /// ```
3171     ///
3172     /// To work around this, we can use [`split_at_mut`] to create two distinct
3173     /// mutable sub-slices from a slice:
3174     ///
3175     /// ```
3176     /// let mut slice = [1, 2, 3, 4, 5];
3177     ///
3178     /// {
3179     ///     let (left, right) = slice.split_at_mut(2);
3180     ///     left.swap_with_slice(&mut right[1..]);
3181     /// }
3182     ///
3183     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3184     /// ```
3185     ///
3186     /// [`split_at_mut`]: slice::split_at_mut
3187     #[stable(feature = "swap_with_slice", since = "1.27.0")]
3188     pub fn swap_with_slice(&mut self, other: &mut [T]) {
3189         assert!(self.len() == other.len(), "destination and source slices have different lengths");
3190         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3191         // checked to have the same length. The slices cannot overlap because
3192         // mutable references are exclusive.
3193         unsafe {
3194             ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3195         }
3196     }
3197
3198     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3199     fn align_to_offsets<U>(&self) -> (usize, usize) {
3200         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3201         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3202         //
3203         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3204         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3205         // place of every 3 Ts in the `rest` slice. A bit more complicated.
3206         //
3207         // Formula to calculate this is:
3208         //
3209         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3210         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3211         //
3212         // Expanded and simplified:
3213         //
3214         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3215         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3216         //
3217         // Luckily since all this is constant-evaluated... performance here matters not!
3218         #[inline]
3219         fn gcd(a: usize, b: usize) -> usize {
3220             use crate::intrinsics;
3221             // iterative stein’s algorithm
3222             // We should still make this `const fn` (and revert to recursive algorithm if we do)
3223             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
3224
3225             // SAFETY: `a` and `b` are checked to be non-zero values.
3226             let (ctz_a, mut ctz_b) = unsafe {
3227                 if a == 0 {
3228                     return b;
3229                 }
3230                 if b == 0 {
3231                     return a;
3232                 }
3233                 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
3234             };
3235             let k = ctz_a.min(ctz_b);
3236             let mut a = a >> ctz_a;
3237             let mut b = b;
3238             loop {
3239                 // remove all factors of 2 from b
3240                 b >>= ctz_b;
3241                 if a > b {
3242                     mem::swap(&mut a, &mut b);
3243                 }
3244                 b = b - a;
3245                 // SAFETY: `b` is checked to be non-zero.
3246                 unsafe {
3247                     if b == 0 {
3248                         break;
3249                     }
3250                     ctz_b = intrinsics::cttz_nonzero(b);
3251                 }
3252             }
3253             a << k
3254         }
3255         let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
3256         let ts: usize = mem::size_of::<U>() / gcd;
3257         let us: usize = mem::size_of::<T>() / gcd;
3258
3259         // Armed with this knowledge, we can find how many `U`s we can fit!
3260         let us_len = self.len() / ts * us;
3261         // And how many `T`s will be in the trailing slice!
3262         let ts_len = self.len() % ts;
3263         (us_len, ts_len)
3264     }
3265
3266     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3267     /// maintained.
3268     ///
3269     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3270     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3271     /// length possible for a given type and input slice, but only your algorithm's performance
3272     /// should depend on that, not its correctness. It is permissible for all of the input data to
3273     /// be returned as the prefix or suffix slice.
3274     ///
3275     /// This method has no purpose when either input element `T` or output element `U` are
3276     /// zero-sized and will return the original slice without splitting anything.
3277     ///
3278     /// # Safety
3279     ///
3280     /// This method is essentially a `transmute` with respect to the elements in the returned
3281     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3282     ///
3283     /// # Examples
3284     ///
3285     /// Basic usage:
3286     ///
3287     /// ```
3288     /// unsafe {
3289     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3290     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3291     ///     // less_efficient_algorithm_for_bytes(prefix);
3292     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3293     ///     // less_efficient_algorithm_for_bytes(suffix);
3294     /// }
3295     /// ```
3296     #[stable(feature = "slice_align_to", since = "1.30.0")]
3297     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3298         // Note that most of this function will be constant-evaluated,
3299         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
3300             // handle ZSTs specially, which is – don't handle them at all.
3301             return (self, &[], &[]);
3302         }
3303
3304         // First, find at what point do we split between the first and 2nd slice. Easy with
3305         // ptr.align_offset.
3306         let ptr = self.as_ptr();
3307         // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3308         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3309         if offset > self.len() {
3310             (self, &[], &[])
3311         } else {
3312             let (left, rest) = self.split_at(offset);
3313             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3314             // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3315             // since the caller guarantees that we can transmute `T` to `U` safely.
3316             unsafe {
3317                 (
3318                     left,
3319                     from_raw_parts(rest.as_ptr() as *const U, us_len),
3320                     from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3321                 )
3322             }
3323         }
3324     }
3325
3326     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3327     /// maintained.
3328     ///
3329     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3330     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3331     /// length possible for a given type and input slice, but only your algorithm's performance
3332     /// should depend on that, not its correctness. It is permissible for all of the input data to
3333     /// be returned as the prefix or suffix slice.
3334     ///
3335     /// This method has no purpose when either input element `T` or output element `U` are
3336     /// zero-sized and will return the original slice without splitting anything.
3337     ///
3338     /// # Safety
3339     ///
3340     /// This method is essentially a `transmute` with respect to the elements in the returned
3341     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3342     ///
3343     /// # Examples
3344     ///
3345     /// Basic usage:
3346     ///
3347     /// ```
3348     /// unsafe {
3349     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3350     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3351     ///     // less_efficient_algorithm_for_bytes(prefix);
3352     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3353     ///     // less_efficient_algorithm_for_bytes(suffix);
3354     /// }
3355     /// ```
3356     #[stable(feature = "slice_align_to", since = "1.30.0")]
3357     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3358         // Note that most of this function will be constant-evaluated,
3359         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
3360             // handle ZSTs specially, which is – don't handle them at all.
3361             return (self, &mut [], &mut []);
3362         }
3363
3364         // First, find at what point do we split between the first and 2nd slice. Easy with
3365         // ptr.align_offset.
3366         let ptr = self.as_ptr();
3367         // SAFETY: Here we are ensuring we will use aligned pointers for U for the
3368         // rest of the method. This is done by passing a pointer to &[T] with an
3369         // alignment targeted for U.
3370         // `crate::ptr::align_offset` is called with a correctly aligned and
3371         // valid pointer `ptr` (it comes from a reference to `self`) and with
3372         // a size that is a power of two (since it comes from the alignement for U),
3373         // satisfying its safety constraints.
3374         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3375         if offset > self.len() {
3376             (self, &mut [], &mut [])
3377         } else {
3378             let (left, rest) = self.split_at_mut(offset);
3379             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3380             let rest_len = rest.len();
3381             let mut_ptr = rest.as_mut_ptr();
3382             // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3383             // SAFETY: see comments for `align_to`.
3384             unsafe {
3385                 (
3386                     left,
3387                     from_raw_parts_mut(mut_ptr as *mut U, us_len),
3388                     from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3389                 )
3390             }
3391         }
3392     }
3393
3394     /// Checks if the elements of this slice are sorted.
3395     ///
3396     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3397     /// slice yields exactly zero or one element, `true` is returned.
3398     ///
3399     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3400     /// implies that this function returns `false` if any two consecutive items are not
3401     /// comparable.
3402     ///
3403     /// # Examples
3404     ///
3405     /// ```
3406     /// #![feature(is_sorted)]
3407     /// let empty: [i32; 0] = [];
3408     ///
3409     /// assert!([1, 2, 2, 9].is_sorted());
3410     /// assert!(![1, 3, 2, 4].is_sorted());
3411     /// assert!([0].is_sorted());
3412     /// assert!(empty.is_sorted());
3413     /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3414     /// ```
3415     #[inline]
3416     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3417     pub fn is_sorted(&self) -> bool
3418     where
3419         T: PartialOrd,
3420     {
3421         self.is_sorted_by(|a, b| a.partial_cmp(b))
3422     }
3423
3424     /// Checks if the elements of this slice are sorted using the given comparator function.
3425     ///
3426     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3427     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3428     /// [`is_sorted`]; see its documentation for more information.
3429     ///
3430     /// [`is_sorted`]: slice::is_sorted
3431     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3432     pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
3433     where
3434         F: FnMut(&T, &T) -> Option<Ordering>,
3435     {
3436         self.iter().is_sorted_by(|a, b| compare(*a, *b))
3437     }
3438
3439     /// Checks if the elements of this slice are sorted using the given key extraction function.
3440     ///
3441     /// Instead of comparing the slice's elements directly, this function compares the keys of the
3442     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3443     /// documentation for more information.
3444     ///
3445     /// [`is_sorted`]: slice::is_sorted
3446     ///
3447     /// # Examples
3448     ///
3449     /// ```
3450     /// #![feature(is_sorted)]
3451     ///
3452     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3453     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3454     /// ```
3455     #[inline]
3456     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3457     pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
3458     where
3459         F: FnMut(&T) -> K,
3460         K: PartialOrd,
3461     {
3462         self.iter().is_sorted_by_key(f)
3463     }
3464
3465     /// Returns the index of the partition point according to the given predicate
3466     /// (the index of the first element of the second partition).
3467     ///
3468     /// The slice is assumed to be partitioned according to the given predicate.
3469     /// This means that all elements for which the predicate returns true are at the start of the slice
3470     /// and all elements for which the predicate returns false are at the end.
3471     /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
3472     /// (all odd numbers are at the start, all even at the end).
3473     ///
3474     /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3475     /// as this method performs a kind of binary search.
3476     ///
3477     /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3478     ///
3479     /// [`binary_search`]: slice::binary_search
3480     /// [`binary_search_by`]: slice::binary_search_by
3481     /// [`binary_search_by_key`]: slice::binary_search_by_key
3482     ///
3483     /// # Examples
3484     ///
3485     /// ```
3486     /// let v = [1, 2, 3, 3, 5, 6, 7];
3487     /// let i = v.partition_point(|&x| x < 5);
3488     ///
3489     /// assert_eq!(i, 4);
3490     /// assert!(v[..i].iter().all(|&x| x < 5));
3491     /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3492     /// ```
3493     #[stable(feature = "partition_point", since = "1.52.0")]
3494     pub fn partition_point<P>(&self, mut pred: P) -> usize
3495     where
3496         P: FnMut(&T) -> bool,
3497     {
3498         self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
3499     }
3500 }
3501
3502 trait CloneFromSpec<T> {
3503     fn spec_clone_from(&mut self, src: &[T]);
3504 }
3505
3506 impl<T> CloneFromSpec<T> for [T]
3507 where
3508     T: Clone,
3509 {
3510     default fn spec_clone_from(&mut self, src: &[T]) {
3511         assert!(self.len() == src.len(), "destination and source slices have different lengths");
3512         // NOTE: We need to explicitly slice them to the same length
3513         // to make it easier for the optimizer to elide bounds checking.
3514         // But since it can't be relied on we also have an explicit specialization for T: Copy.
3515         let len = self.len();
3516         let src = &src[..len];
3517         for i in 0..len {
3518             self[i].clone_from(&src[i]);
3519         }
3520     }
3521 }
3522
3523 impl<T> CloneFromSpec<T> for [T]
3524 where
3525     T: Copy,
3526 {
3527     fn spec_clone_from(&mut self, src: &[T]) {
3528         self.copy_from_slice(src);
3529     }
3530 }
3531
3532 #[stable(feature = "rust1", since = "1.0.0")]
3533 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
3534 impl<T> const Default for &[T] {
3535     /// Creates an empty slice.
3536     fn default() -> Self {
3537         &[]
3538     }
3539 }
3540
3541 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3542 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
3543 impl<T> const Default for &mut [T] {
3544     /// Creates a mutable empty slice.
3545     fn default() -> Self {
3546         &mut []
3547     }
3548 }
3549
3550 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
3551 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`.  At a future
3552 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
3553 /// `str`) to slices, and then this trait will be replaced or abolished.
3554 pub trait SlicePattern {
3555     /// The element type of the slice being matched on.
3556     type Item;
3557
3558     /// Currently, the consumers of `SlicePattern` need a slice.
3559     fn as_slice(&self) -> &[Self::Item];
3560 }
3561
3562 #[stable(feature = "slice_strip", since = "1.51.0")]
3563 impl<T> SlicePattern for [T] {
3564     type Item = T;
3565
3566     #[inline]
3567     fn as_slice(&self) -> &[Self::Item] {
3568         self
3569     }
3570 }
3571
3572 #[stable(feature = "slice_strip", since = "1.51.0")]
3573 impl<T, const N: usize> SlicePattern for [T; N] {
3574     type Item = T;
3575
3576     #[inline]
3577     fn as_slice(&self) -> &[Self::Item] {
3578         self
3579     }
3580 }