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