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