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