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