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